Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Retrieve HTTP Status Code with Guzzle?

New to Guzzle/Http.

I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.

I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).

This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )

namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;

$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';

try {

    $res = $client->request('POST', $url, [
        'form_params' => [
            'username' => 'abc',
            'password' => '123'                     
        ]
    ]);

} catch (ClientException $e) {

    //echo Psr7\str($e->getRequest());
    echo Psr7\str($e->getResponse());

}
like image 785
sineverba Avatar asked May 02 '18 12:05

sineverba


People also ask

How do I send HTTP request using guzzle?

Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);

How do I debug guzzle request?

Debugging when using Guzzle, is quiet easy by providing the debug key in the payload: $client->request('GET', '/url, ['debug' => true]); This is quiet easy and not an issue if your are not passing any body content, using only query string to dump what's been request.

What is HTTP status code1?

Prevailing theory is that the status is set to null and the statuscode set to -1 when the response object is constructed, and then something happens to the connection that means the request doesn't complete, so these defaults are never overwritten with real values.


1 Answers

You can use the getStatusCode function.

$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();

Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.

// On client creation
$client = new GuzzleHttp\Client([
  'allow_redirects' => false
]);

// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);

If you want to check status code in catch block, then you need to use $exception->getCode()

  • More about responses
  • More about allow_redirects
like image 191
Scofield Avatar answered Oct 18 '22 23:10

Scofield