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


基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01