Questa pagina fornisce una rapida introduzione a Guzzle ed esempi introduttivi. Se non avete ancora installato Guzzle, andate alla Installation pagina.
Potete inviare richieste con Guzzle usando un oggetto GuzzleHttp\ClientInterface
.
use GuzzleHttp\Client;
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://httpbin.org',
// You can set any number of default request options.
'timeout' => 2.0,
]);
I client sono immutabili in Guzzle, il che significa che non potete cambiare i default usati da un client dopo che è stato creato.
Il costruttore del client accetta un array associativo di opzioni:
base_uri
(string|UriInterface) URI di base del client che viene fuso in URI relativi URI. Può essere una stringa o un'istanza di UriInterface. Quando un URI relativo viene fornito a un client, il client combinerà l'URI di base con l'URI URI relativo usando le regole descritte in RFC 3986, sezione 5.2.
// Creare un client con un URI di base
$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
// Invia una richiesta a https://foo.com/api/test
$response = $client->request('GET', 'test');
// Invia una richiesta a https://foo.com/root
$response = $client->request('GET', '/root');
Non avete voglia di leggere RFC 3986? Ecco alcuni esempi veloci su come un base_uri
viene risolto con un altro URI.
base_uri | URI | Risultato |
---|---|---|
http://foo.com |
/bar |
http://foo.com/bar |
http://foo.com/foo |
/bar |
http://foo.com/bar |
http://foo.com/foo |
bar |
http://foo.com/bar |
http://foo.com/foo/ |
bar |
http://foo.com/foo/bar |
http://foo.com |
http://baz.com |
http://baz.com |
http://foo.com/?bar |
bar |
http://foo.com/bar |
handler
Psr7\Http\Message\RequestInterface
e un array
di opzioni di trasferimento e deve restituire un
GuzzleHttp\Promise\PromiseInterface
che è soddisfatto con un
Psr7\Http\Message\ResponseInterface
al successo....
I metodi magici sul client rendono facile l'invio di richieste sincrone:
$response = $client->get('http://httpbin.org/get');
$response = $client->delete('http://httpbin.org/delete');
$response = $client->head('http://httpbin.org/get');
$response = $client->options('http://httpbin.org/get');
$response = $client->patch('http://httpbin.org/patch');
$response = $client->post('http://httpbin.org/post');
$response = $client->put('http://httpbin.org/put');
Puoi creare una richiesta e poi inviare la richiesta con il cliente quando sei pronto:
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http://httpbin.org/put');
$response = $client->send($request, ['timeout' => 2]);
Gli oggetti client forniscono una grande quantità di flessibilità nel modo in cui le richieste vengono trasferite, incluse le opzioni di richiesta predefinite, il middleware predefinito dello stack del gestore che sono usati da ogni richiesta, e un URI di base che permette di inviare richieste con URI relativi.
Puoi trovare maggiori informazioni sul middleware del client nella pagina Handlers and Middleware della documentazione.
È possibile inviare richieste asincrone utilizzando i metodi magici forniti da un client:
$promise = $client->getAsync('http://httpbin.org/get');
$promise = $client->deleteAsync('http://httpbin.org/delete');
$promise = $client->headAsync('http://httpbin.org/get');
$promise = $client->optionsAsync('http://httpbin.org/get');
$promise = $client->patchAsync('http://httpbin.org/patch');
$promise = $client->postAsync('http://httpbin.org/post');
$promise = $client->putAsync('http://httpbin.org/put');
Potete anche usare i metodi sendAsync() e requestAsync() di un client:
use GuzzleHttp\Psr7\Request;
// Create a PSR-7 request object to send
$headers = ['X-Foo' => 'Bar'];
$body = 'Hello!';
$request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
$promise = $client->sendAsync($request);
// Or, if you don't need to pass in a request instance:
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
La promessa restituita da questi metodi implementa la
Promises/A+ spec, fornita dalla
Guzzle promises library. Questo significa
che è possibile concatenare then()
le chiamate alla promessa. Queste chiamate then sono
soddisfatte con successo Psr\Http\Message\ResponseInterface
o
rifiutato con un'eccezione.
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
È possibile inviare più richieste simultaneamente usando promesse e richieste asincrone.
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\Utils::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\Utils::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];
Potete usare l'oggetto GuzzleHttp\Pool
quando avete una quantità indeterminata di richieste che volete inviare.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
$client = new Client();
$requests = function ($total) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield new Request('GET', $uri);
}
};
$pool = new Pool($client, $requests(100), [
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) {
// this is delivered each successful response
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
Oppure usando una chiusura che restituirà una promessa una volta che il pool chiama la chiusura.
$client = new Client();
$requests = function ($total) use ($client) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield function() use ($client, $uri) {
return $client->getAsync($uri);
};
}
};
$pool = new Pool($client, $requests(100));
Negli esempi precedenti, abbiamo recuperato una variabile $response
o ci è stata
consegnato una risposta da una promessa. L'oggetto response implementa una PSR-7
response, Psr\Http\Message\ResponseInterface
, e contiene molte
informazioni utili.
Potete ottenere il codice di stato e la frase di motivazione della risposta:
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
È possibile recuperare le intestazioni dalla risposta:
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}
// Get a header from the response.
echo $response->getHeader('Content-Length')[0];
// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
Il corpo di una risposta può essere recuperato usando il metodo getBody
. Il corpo può essere usato come una stringa, castato a una stringa, o usato come un oggetto simile a un flusso.
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();
È possibile fornire parametri di query string con una richiesta in diversi modi.
È possibile impostare i parametri della query string nell'URI della richiesta:
$response = $client->request('GET', 'http://httpbin.org?foo=bar');
Puoi specificare i parametri della stringa di query usando l'opzione di richiesta query
come un array.
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Fornire l'opzione come array userà la funzione http_build_query
di PHP per formattare la stringa della query.
E infine, potete fornire l'opzione di richiesta query
come una stringa.
$client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
Guzzle fornisce diversi metodi per caricare i dati.
È possibile inviare richieste che contengono un flusso di dati passando una stringa,
risorsa restituita da fopen
, o un'istanza di un
Psr\Http\Message\StreamInterface
all'opzione di richiesta body
.
use GuzzleHttp\Psr7;
// Provide the body as a string.
$r = $client->request('POST', 'http://httpbin.org/post', [
'body' => 'raw data'
]);
// Provide an fopen resource.
$body = Psr7\Utils::tryFopen('/path/to/file', 'r');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
// Use the Utils::streamFor method to create a PSR-7 stream.
$body = Psr7\Utils::streamFor('hello!');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
Un modo semplice per caricare dati JSON e impostare l'intestazione appropriata è usare l'opzione di richiesta json
:
$r = $client->request('PUT', 'http://httpbin.org/put', [
'json' => ['foo' => 'bar']
]);
Oltre a specificare i dati grezzi di una richiesta usando l'opzione di richiesta body
, Guzzle fornisce utili astrazioni sull'invio di dati POST.
L'invio di richieste application/x-www-form-urlencoded
POST richiede di specificare i campi POST come array nelle opzioni di richiesta form_params
.
$response = $client->request('POST', 'http://httpbin.org/post', [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
È possibile inviare file insieme a un modulo (multipart/form-data
richieste POST),
usando l'opzione di richiesta multipart
. multipart
accetta un array di
array associativi, dove ogni array associativo contiene le seguenti chiavi:
Psr\Http\Message\StreamInterface
per trasmettere
il contenuto da un flusso PSR-7.use GuzzleHttp\Psr7;
$response = $client->request('POST', 'http://httpbin.org/post', [
'multipart' => [
[
'name' => 'field_name',
'contents' => 'abc'
],
[
'name' => 'file_name',
'contents' => Psr7\Utils::tryFopen('/path/to/file', 'r')
],
[
'name' => 'other_file',
'contents' => 'hello',
'filename' => 'filename.txt',
'headers' => [
'X-Foo' => 'this is an extra header to include'
]
]
]
]);
Guzzle può mantenere una sessione di cookie per voi se istruito usando l'opzione
cookies
opzione di richiesta. Quando si invia una richiesta, l'opzione cookies
deve essere impostata su un'istanza di GuzzleHttp\Cookie\CookieJarInterface
.
// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
'cookies' => $jar
]);
Potete impostare cookies
su true
in un costruttore di client se volete usare un contenitore di cookie condiviso per tutte le richieste.
// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');
Esistono diverse implementazioni per la GuzzleHttpCookie\CookieJarInterface
:
GuzzleHttp\Cookie\CookieJar
memorizza i cookie come un array.GuzzleHttp\Cookie\FileCookieJar
persiste i cookie non di sessione
usando un file formattato JSON.GuzzleHttp\Cookie\SessionCookieJar
persiste i cookie nella
sessione del client.Puoi impostare manualmente i cookie in un vaso di cookie con il costruttore chiamato fromArray(array $cookies, $domain)
.
$jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
[
'some_cookie' => 'foo',
'other_cookie' => 'barbaz1234'
],
'example.org'
);
Potete ottenere un cookie dal suo nome con il metodo getCookieByName($name)
che restituisce un'istanza di GuzzleHttp\Cookie\SetCookie
.
$cookie = $jar->getCookieByName('some_cookie');
$cookie->getValue(); // 'foo'
$cookie->getDomain(); // 'example.org'
$cookie->getExpires(); // expiration date as a Unix timestamp
I cookie possono anche essere recuperati in un array grazie al metodo toArray().
L'interfaccia GuzzleHttp\Cookie\CookieJarInterface
estende
Traversable
in modo che possa essere iterata in un ciclo foreach.
Guzzle seguirà automaticamente i redirect a meno che non gli diciate di non farlo. Potete personalizzare il comportamento dei redirect usando l'opzione di richiesta allow_redirects
.
true
per abilitare i redirect normali con un numero massimo di 5
redirect. Questa è l'impostazione predefinita.false
per disabilitare i redirect.$response = $client->request('GET', 'http://github.com');
echo $response->getStatusCode();
// 200
L'esempio seguente mostra che i reindirizzamenti possono essere disabilitati.
$response = $client->request('GET', 'http://github.com', [
'allow_redirects' => false
]);
echo $response->getStatusCode();
// 301
Vista ad albero
La seguente vista ad albero descrive come le Guzzle Exceptions dipendono l'una dall'altra.
. \RuntimeException
└── TransferException (implements GuzzleException)
├── ConnectException (implements NetworkExceptionInterface)
└── RequestException
├── BadResponseException
│ ├── ServerException
│ └── ClientException
└── TooManyRedirectsException
Guzzle lancia eccezioni per gli errori che si verificano durante un trasferimento.
Un'eccezione GuzzleHttp\ExceptionConnectException
viene lanciata in
caso di un errore di rete. Questa eccezione si estende da
GuzzleHttp\Exception\TransferException
.
Una GuzzleHttp\ExceptionClientException
viene lanciata per errori di livello 400
se l'opzione di richiesta http_errors
è impostata a true. Questa
eccezione si estende da GuzzleHttp\ExceptionBadResponseException
e
GuzzleHttp\ExceptionBadResponseException
estende da
GuzzleHttp\Exception\RequestException
.
use GuzzleHttp\Psr7;
usa GuzzleHttp\Exception\ClientException;
try {
$client->request('GET', 'https://github.com/_abc_123_404');
} catch (ClientException $e) {
echo Psr7\Message::toString($e->getRequest());
echo Psr7\Message::toString($e->getResponse());
}
Un GuzzleHttp\Exception\ServerException
viene lanciato per errori di livello 500
se l'opzione di richiesta http_errors
è impostata a true. Questa
eccezione si estende da GuzzleHttp\ExceptionBadResponseException
.
Una GuzzleHttp\Exception\TooManyRedirectsException
viene lanciata quando troppi
troppi redirect sono seguiti. Questa eccezione si estende da GuzzleHttp\Exception\RequestException
.
Tutte le eccezioni di cui sopra si estendono da GuzzleHttp\Exception\TransferException
.
Guzzle espone alcune variabili d'ambiente che possono essere utilizzate per personalizzare il comportamento della libreria.
GUZZLE_CURL_SELECT_TIMEOUT
curl_multi_select()
. Alcuni sistemi
hanno problemi con l'implementazione di PHP di curl_multi_select()
dove
chiamando questa funzione si ottiene sempre l'attesa per la durata massima del
del timeout.HTTP_PROXY
Definisce il proxy da usare quando si inviano richieste utilizzando il protocollo "http".
Nota: poiché la variabile HTTP_PROXY può contenere input arbitrari dell'utente su alcuni ambienti (CGI), la variabile è usata solo su CLI SAPI. Vedi https://httpoxy.org per maggiori informazioni.
HTTPS_PROXY
NO_PROXY
Guzzle può utilizzare le impostazioni ini di PHP quando configura i client.
openssl.cafile