如何在数组中包装guzzle json帖子正文

时间:2019-03-21 01:22:43

标签: laravel guzzle

我在使用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]);

对我来说一切似乎都很好。过去,我曾经用这种方式来吃。但是,服务器将响应“未提交任何数据”消息。

请求:

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"},有人知道如何用枪口复制它吗?

1 个答案:

答案 0 :(得分:0)

我能够通过将有效载荷包装在一个数组中来解决此问题,如下所示: $ payload = [[''名称'=>'测试名称']];