Tập chọt Psr-7 Guzzle, Guzzle7 and HTTPClient
30th Jun 2022If you're sending a request to a custom URL in Drupal 8/9, you might be tempted to implement a solution using cURL or another library. However, Drupal core comes with Guzzle, a "PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services." As with most things in Drupal, it's not obvious how to use something immediately, so here's a demo to show you how to take care of sending a request to an arbitrary URL inside a custom Drupal module. You might use this example class to display a status code on some page
No. 1
<?php namespace Drupal\custom_guzzle_request\Http; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Drupal\Core\StringTranslation\TranslationInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; /** * Get a response code from any URL using Guzzle in Drupal 8! * * Usage: * In the head of your document: * * use Drupal\custom_guzzle_request\Http\CustomGuzzleHttp; * * In the area you want to return the result, using any URL for $url: * * $check = new CustomGuzzleHttp(); * $response = $check->performRequest($url); * **/ class CustomGuzzleHttp { use StringTranslationTrait; public function performRequest($siteUrl) { $client = new \GuzzleHttp\Client(); try { $res = $client->get($siteUrl, ['http_errors' => false]); return($res->getStatusCode()); } catch (RequestException $e) { return($this->t('Error')); } } }
No 2.
use GuzzleHttp\Client; $url = 'http://www.domain.drupal'; $content_client = new Client([ 'base_uri' => $url, 'timeout' => 20.0, ]); $headers = [ 'Content-type' => 'application/vnd.api+json', 'Accept' => 'application/vnd.api+json' ]; $payload['data'] = [ 'type' => 'node--article', 'attributes' => [ "title" => "My custom title", "body" => [ "value" => "Custom value", "format" => "plain_text" ] ] ]; $guzzleResponse = $content_client->post('/jsonapi/node/article/71adf560-044c-49e0-9461-af593bad0746', [ 'json' => json_encode($payload), 'headers' => $headers ]); if ($guzzleResponse->getStatusCode() == 200) { $response = json_decode($guzzleResponse->getBody()); }
Guzzle7 (same works for Guzzle 6 as well)
Using RequestException, RequestException catches any exception that can be thrown while transferring requests.
try{ $client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]); $guzzleResponse = $client->get('/foobar'); // or can use // $guzzleResponse = $client->request('GET', '/foobar') if ($guzzleResponse->getStatusCode() == 200) { $response = json_decode($guzzleResponse->getBody(),true); //perform your action with $response } } catch(\GuzzleHttp\Exception\RequestException $e){ // you can catch here 400 response errors and 500 response errors // You can either use logs here use Illuminate\Support\Facades\Log; $error['error'] = $e->getMessage(); $error['request'] = $e->getRequest(); if($e->hasResponse()){ if ($e->getResponse()->getStatusCode() == '400'){ $error['response'] = $e->getResponse(); } } Log::error('Error occurred in get request.', ['error' => $error]); }catch(Exception $e){ //other errors } Psr7 Guzzle use GuzzleHttp\Psr7; use GuzzleHttp\Exception\RequestException; try { $client->request('GET', '/foo'); } catch (RequestException $e) { $error['error'] = $e->getMessage(); $error['request'] = Psr7\Message::toString($e->getRequest()); if ($e->hasResponse()) { $error['response'] = Psr7\Message::toString($e->getResponse()); } Log::error('Error occurred in get request.', ['error' => $error]); }
For HTTPClient
use Illuminate\Support\Facades\Http; try{ $response = Http::get('http://api.foo.com'); if($response->successful()){ $reply = $response->json(); } if($response->failed()){ if($response->clientError()){ //catch all 400 exceptions Log::debug('client Error occurred in get request.'); $response->throw(); } if($response->serverError()){ //catch all 500 exceptions Log::debug('server Error occurred in get request.'); $response->throw(); } } }catch(Exception $e){ //catch the exception here }
Add new comment