我对API和guzzle有困难。 API需要json内容类型和基本身份验证。 api示例请求是
POST /endpoint/v1/create?id=1
[
{
"Name": "Test Room"
}
]
我的代码:
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Middleware;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7;
$client = new Client(['base_uri' => env('base_uri')]);
$headers = [
'Authorization' => 'Basic',
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
$uri='/endpoint/v1/create?id=' . env('id');
$payload = ['Name' => 'Test Name'];
$response = $this->client->request('POST', $uri, ['auth' => ['username', 'password'], 'headers' => $headers, 'json' => $payload]);
一切对我来说都很好。过去我曾用过这种方式。但是,服务器响应“无数据已提交”消息。
请求:
POST /endpoint/v1/create?id=1 HTTP/1.1
User-Agent: GuzzleHttp/6.3.3 curl/7.58.0 PHP/7.2.5-1+ubuntu18.04.1+deb.sury.org+1
Authorization: Basic {Auth basic string goes here}
Host: {host goes here}
Accept: application/json
Content-Type: application/json
{"Name":"Test Name"}
响应:
HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
WWW-Authenticate: Basic
Date: Thu, 21 Mar 2019 01:04:21 GMT
Content-Length: 36
{"Message":"No data was submitted."}
编辑:我能够在邮递员中成功完成此请求。 API响应[{"Name":"Test Name"}]
而不是{"Name":"Test Name"}
,是否有人知道如何用guzzle复制它?
我能够通过将有效负载包装在如下数组中来解决这个问题:$ payload = [['Name'=>'Test Name']];