【问题标题】:Guzzle PUT request auth errorGuzzle PUT 请求身份验证错误
【发布时间】:2017-06-01 13:09:36
【问题描述】:

我有以下代码使用来自另一个系统的 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;
}

【问题讨论】:

  • 您能否展示您已通过邮递员成功发送的示例请求(无需确切数据)?
  • @shudder - 我在问题中添加了,请验证

标签: php laravel-5 put guzzle


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 2017-06-01
    • 2020-10-15
    • 2023-02-26
    • 2016-11-14
    • 2018-02-26
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多