php - Guzzle HTTP 请求从 POST 转换为 GET

标签 php guzzle

我在尝试向外部 API 发布帖子时发生了一件非常奇怪的事情,我尝试向 URL 发出 POST 请求,但 Guzzle 改为发出 GET 请求(这是对该 API 的合法操作,但返回的内容不同)。

这是代码:

$request = $this->client->createRequest('POST', 'sessions', [
  'json' => [
    'agent_id' => $agentId,
    'url' => $url
  ],
  'query' => [
    'api_key' => $this->apiKey
  ]
]);

echo $request->getMethod(); // comes out as POST
$response = $this->client->send($request);
echo $request->getMethod(); // suddenly becomes GET

当我使用 $this-client->post(…) 时也会发生同样的事情

我真的不知道接下来要做什么。

最佳答案

我遇到了同样的问题。
原因是当存在代码为 301 或 302 的位置重定向时,Guzzle 将请求方法更改为“GET”。
我在 RedirectMiddleware.php 中找到了“问题代码”。
但是当您看到 if 条件时,您可以通过将 'allow_redirects'=>['strict'=>true] 添加到您的选项来禁用此行为。
找到这个选项后,我发现该选项被列在了Guzzle Options Documentation
所以你只需像这样重写你的 createRequest :

$request = $this->client->createRequest('POST', 'sessions', [
  'json' => [
    'agent_id' => $agentId,
    'url' => $url
  ],
  'query' => [
    'api_key' => $this->apiKey
  ],
  'allow_redirects'=> ['strict'=>true]
]); 
并且它应该在重定向后保持 Method POST

关于php - Guzzle HTTP 请求从 POST 转换为 GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29470839/

相关文章:

php - 使用 Tumblr PHP API 时出现 fatal error cURL 错误 60

php - 我们如何在 Guzzle 中指定 TLS/SSL 选项?

php - 使用 mailgun PHP API 发送电子邮件

php - 从 Guzzle 响应消息中获取 http header 作为字符串

PHP 命名空间和动态类名

php - 使用 jQuery 的日期选择器

laravel - 在 Laravel 中将 Multipart 和 Json 与 Guzzle 一起发布

php - Symfony2 集成测试中的用户 token

php - 我无法在 Bootstrap 中获取有错误文本字段

php - 使用 $_FILES 和 PHP 上传文件