簡體   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