Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guzzle HTTP request transforms from POST to GET

Tags:

php

guzzle

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.

like image 511
Dan F. Avatar asked Apr 06 '15 11:04

Dan F.


2 Answers

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.

like image 83
Radon8472 Avatar answered Sep 24 '22 14:09

Radon8472


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.

like image 34
Hirnhamster Avatar answered Sep 23 '22 14:09

Hirnhamster