我在尝试向外部 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/