guzzle connectionexception code example

Example 1: guzzle catch exceptions

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ConnectException;

$client = new Client();

try{
	$response = $client->request('GET', 'http://github.com');
}
catch (ConnectException $e) {
	// Connection exceptions are not caught by RequestException
	echo "Internet, DNS, or other connection error\n";
    die;
}
catch (RequestException $e) {
	echo "Request Exception\n";
    die;
}
// deal with your $reponse here

Example 2: concurrent requests guzzle

use GuzzleHttp\Client;
use GuzzleHttp\Promise;

$client = new Client(['base_uri' => 'http://httpbin.org/']);

// Initiate each request but do not block
$promises = [
    'image' => $client->getAsync('/image'),
    'png'   => $client->getAsync('/image/png'),
    'jpeg'  => $client->getAsync('/image/jpeg'),
    'webp'  => $client->getAsync('/image/webp')
];

// Wait for the requests to complete; throws a ConnectException
// if any of the requests fail
$responses = Promise\unwrap($promises);

// You can access each response using the key of the promise
echo $responses['image']->getHeader('Content-Length')[0];
echo $responses['png']->getHeader('Content-Length')[0];

// Wait for the requests to complete, even if some of them fail
$responses = Promise\settle($promises)->wait();

// Values returned above are wrapped in an array with 2 keys: "state" (either fulfilled or rejected) and "value" (contains the response)
echo $responses['image']['state']; // returns "fulfilled"
echo $responses['image']['value']->getHeader('Content-Length')[0];
echo $responses['png']['value']->getHeader('Content-Length')[0];

Example 3: post request data not getting from guzzle laravel

use Illuminate\Support\Facades\Http;

Http::fake();

$response = Http::post(...);

Tags:

Php Example