POST 请求适用于 Postman,但不适用于 Guzzle

2022-01-22 00:00:00 json postman php laravel guzzle

在我的 Laravel 应用程序中,我需要定期使用 Guzzle 将数据 POST 到 API.

In my Laravel application, I periodically need to POST data to an API using Guzzle.

API 使用不记名令牌进行身份验证,并请求和接受原始 json.为了测试,我使用 Postman 访问了 API,一切运行良好.

The API users a bearer token to authenticate, and requests and accepts raw json. To test, I accessed the API using Postman, and everything worked wonderfully.

邮递员标题:

Accept:application/json
Authorization:Bearer [token]
Content-Type:application/json

还有邮递员的身体:

{
    "request1" : "123456789",
    "request2" : "2468",
    "request3" : "987654321",
    "name" : "John Doe"
}

Postman 返回一个 200 和一个 JSON 对象作为响应.

Postman returns a 200, and a JSON object as a response.

现在,当我尝试使用 Guzzle 进行相同操作时,我得到一个 200 状态代码,但没有返回任何 JSON 对象.这是我的 Guzzle 实现:

Now, when I try the same with Guzzle, I get a 200 status code, but no JSON object gets returned. Here's my Guzzle implementation:

public function getClient($token)
{
    return new Client([
        'base_uri' => env('API_HOST'),
        'Accept' => 'application/json',
        'Authorization' => 'Bearer ' . $token,
        'Content-Type' => 'application/json'
    ]);
}

$post = $client->request('POST', '/path/to/api', [
    'json' => [
        'request1' => 123456789,
        'request2' => 2468,
        'request3' => 987654321,
        'name' => 'John Doe',
    ]
]);

使用 Guzzle 发布 JSON 有什么技巧吗?如果没有,有没有办法调试引擎盖下发生的事情?

Is there some trick to POSTing JSON with Guzzle? If not, is there a way to debug what's going on under the hood?

我这辈子都无法理解 Postman POST 和 Guzzle POST 之间的区别.

I cannot, for the life of me, understand what the difference is between the Postman POST and the Guzzle POST.

推荐答案

你必须使用 headers 配置部分作为标题,而不是根级别.

You have to use headers config sections for headers, not the root level.

return new Client([
    'base_uri' => env('API_HOST'),
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer ' . $token,
        'Content-Type' => 'application/json',
    ],
]);

相关文章