POST Request适用于Postman,但不适用于Guzzle [英] POST Request works with Postman, but not with Guzzle
问题描述
在我的Laravel应用程序中,我定期需要使用Guzzle将数据发布到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.
Postman标头:
Postman Headers:
Accept:application/json
Authorization:Bearer [token]
Content-Type:application/json
和邮递员身体:
{
"request1" : "123456789",
"request2" : "2468",
"request3" : "987654321",
"name" : "John Doe"
}
邮递员返回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?
我一生无法理解邮递员POST和邮递员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',
],
]);
这篇关于POST Request适用于Postman,但不适用于Guzzle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!