我有以下代码使用来自其他系统的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;
}
答案 0 :(得分:1)
\GuzzleHttp\Psr7\Request
中的第三个参数仅适用于头数组,因此您不会以这种方式发送请求体(第4个arg)。最简单的方法是将此数组作为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();