当我尝试向外部 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”。
我在中找到了“问题代码”重定向中间件.php https://github.com/guzzle/guzzle/blob/a88a06be44e3763213a3ecda2fab9bfbcb8cb356/src/RedirectMiddleware.php#L167.
但是当您看到 if 条件时,您可以通过添加来禁用此行为'allow_redirects'=>['strict'=>true]
您的选择。
找到这个选项后,我发现该选项列在Guzzle 选项文档 http://docs.guzzlephp.org/en/stable/request-options.html#allow-redirects
所以你需要像这样重写你的createRequest:
$request = $this->client->createRequest('POST', 'sessions', [
'json' => [
'agent_id' => $agentId,
'url' => $url
],
'query' => [
'api_key' => $this->apiKey
],
'allow_redirects'=> ['strict'=>true]
]);
它应该保留方法POST
重定向后。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)