Guzzle HTTP 请求从 POST 转换为 GET

Dan*_* F. 5 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
Run Code Online (Sandbox Code Playgroud)

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

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

Rad*_*472 6

我遇到了同样的问题。原因是当存在代码为 301 或 302 的位置重定向时,Guzzle 将请求方法更改为“GET”。我在RedirectMiddleware.php 中找到了“问题代码” 。

但是当您看到 if 条件时,您可以通过添加'allow_redirects'=>['strict'=>true]到您的选项来禁用此行为。找到这个选项后,我发现这个选项列在Guzzle Options 文档中

所以你只需像这样重写你的 createRequest :

$request = $this->client->createRequest('POST', 'sessions', [
  'json' => [
    'agent_id' => $agentId,
    'url' => $url
  ],
  'query' => [
    'api_key' => $this->apiKey
  ],
  'allow_redirects'=> ['strict'=>true]
]); 
Run Code Online (Sandbox Code Playgroud)

它应该POST在重定向后保持 Method 。


小智 1

尝试将键“query”更改为“body”。