如何在阵列中包裹guzzle json帖子的body



我的API和Guzzle遇到困难。API需要JSON内容类型和基本验证。API示例请求是

POST /endpoint/v1/create?id=1
[
  {
    "Name": "Test Room"
  }
]

我的代码:

use GuzzleHttpClient;
use GuzzleHttpPsr7Request;
use GuzzleHttpMiddleware;
use GuzzleHttpExceptionRequestException;
use GuzzleHttpPsr7;
$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."}

编辑:我能够在Postman中成功完成此请求。API对[{"Name":"Test Name"}]响应,但没有{"Name":"Test Name"},有人知道如何用Guzzle复制它吗?

我能够通过将有效载荷包裹在类似的数组中来解决此问题:$ paryload = [['name'=>'测试名称'];

最新更新