简体   繁体   中英

Guzzle HTTP request transforms from POST to GET

I have this very weird thing going on when trying to make post to an external API, I try to make a POST request to the URL but Guzzle make a GET request instead (which is a legal action on this API but returns something different).

Here is the code:

$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

Same thing happens when I use $this-client->post(…)

I really have no idea what to do next.

I run into the same problem. the reason is that Guzzle Changes the Request-Method to 'GET' when there is a location Redirect with code 301 or 302. I found the 'Problem-Code' in the RedirectMiddleware.php .

But when you see the if-condition you can disable this behavior by adding 'allow_redirects'=>['strict'=>true] to your options. After finding this option, I discovered that the option is listed in the Guzzle Options Documentation

So yust rewrite your createRequest like this:

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

And it should stay Method POST after the redirect.

You're probably getting a 3xx status code so that that the Redirect subscriber kicks in (redirect is enabled by default). From the docs :

[...] Pass an associative array containing the 'max' key to specify the maximum number of redirects and optionally provide a 'strict' key value to specify whether or not to use strict RFC compliant redirects ( meaning redirect POST requests with POST requests vs. doing what most browsers do which is redirect POST requests with GET requests ).

//edit Just saw you kinda answered that yourself in the question comments - still leaving this answer online as it provides some context.

尝试将键“查询”更改为“正文”。

Please switch query to form_params . In Guzzle 6 it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM