POST Request works with Postman, but not with Guzzle

吃可爱长大的小学妹 提交于 2019-12-22 05:32:01

问题


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

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.

Postman Headers:

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

And Postman Body:

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

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

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',
    ]
]);

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

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


回答1:


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',
    ],
]);


来源:https://stackoverflow.com/questions/42822951/post-request-works-with-postman-but-not-with-guzzle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!