POST Request works with Postman, but not with Guzzle(POST 请求适用于 Postman,但不适用于 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',
],
]);
这篇关于POST 请求适用于 Postman,但不适用于 Guzzle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:POST 请求适用于 Postman,但不适用于 Guzzle


- SoapClient 设置自定义 HTTP Header 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- Laravel 仓库 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01