繁体   English   中英

Guzzle PUT请求auth错误

[英]Guzzle PUT request auth error

我有以下代码来使用来自其他系统的API保存内容。 我已添加凭据,但显示错误的凭据错误。 它在邮递员工作得很好。

    $client = new GuzzleHttpClient();
try {
  $request = new \GuzzleHttp\Psr7\Request('PUT', config('cms.api.backend') .'/products/'. $nid,
    [
      'auth' => [config('cms.api.user'), config('cms.api.password')],
      'form_params' => [
        'copywrite' => Input::get('copywrite'),
        'status' => $status
      ],
  ]);
  $promise = $client->sendAsync($request)->then(function ($response) {});
  $promise->wait();
}
catch (RequestException $e) {
  $this->logHttpError($e->getResponse()->getStatusCode(), $e->getResponse()->getBody(true));
}

上面的代码有什么问题?

以下是邮递员的导出代码。

$request = new HttpRequest();
$request->setUrl('http://mybackend/api/products/74371');
$request->setMethod(HTTP_METH_PUT);

$request->setHeaders(array(
  'postman-token' => 'e0ddcaea-4787-b2c5-0c52-9aaee860ceac',
  'cache-control' => 'no-cache',
  'authorization' => 'Basic authenticationcode',
  'content-type' => 'application/x-www-form-urlencoded'
));

$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array(
  'copywrite' => 'date to be saved'
));

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}

\\GuzzleHttp\\Psr7\\Request第三个参数仅适用于头数组,因此您不会以这种方式发送请求体(4th arg)。 最简单的方法是将此数组作为sendAsync()方法的第二个参数传递。 它将识别它们, form_params选项将被解析为Content-Type: application/x-www-form-urlencoded标头并为您的请求创建一个有效的流http_build_query()如果您想在请求构造函数中直接执行它,它将使用http_build_query()函数):

$request = new \GuzzleHttp\Psr7\Request('PUT', config('cms.api.backend') .'/products/'. $nid);
$options = [
    'auth' => [config('cms.api.user'), config('cms.api.password')],
    'form_params' => [
        'copywrite' => Input::get('copywrite'),
        'status' => $status
    ],
];


$promise = $client->sendAsync($request, $options)->then(function ($response) {});
$promise->wait();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM