【发布时间】:2019-03-21 01:22:43
【问题描述】:
我在使用 API 时遇到了困难,而且很吃力。 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]);
对我来说一切都很好。我过去曾以这种方式使用过guzzle。但是,服务器以“未提交数据”消息响应。
请求:
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 复制它吗?
【问题讨论】: