current position:Home>Use of PHP HTTP client guzzle 6

Use of PHP HTTP client guzzle 6

2021-08-26 04:59:53 Ian2012

demand

  1. PHP 5.5.0
  2. Use PHP The flow of , allow_url_fopen  Must be in php.ini Enable .
  3. To use cURL, You must already have a version cURL >= 7.19.4, And compiled OpenSSL And zlib.

annotation :PHP Flow and cURL You can choose one of the two ways .

 

install

composer require guzzlehttp/guzzle
     
  • 1.

Use

require 'vendor/autoload.php';
     
  • 1.

Send a request

Mode one :

use GuzzleHttp\Client;

// Create a client with a base URI
$client = new Client(['base_uri' => 'https://foo.com/api/']);
// Send a request to https://foo.com/api/test
$response = $client->request('GET', 'test');
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

Mode two :

$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');
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

Mode three :

use GuzzleHttp\Psr7\Request;

$request = new Request('PUT', 'http://httpbin.org/put');
$response = $client->send($request, ['timeout' => 2]);
     
  • 1.
  • 2.
  • 3.
  • 4.

Mode 4 :( Asynchronous requests )

$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');
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

Methods five :(Promise Asynchronous request for )

use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;

// Create a PSR-7 request object to send
$headers = ['X-Foo' => 'Bar'];
$body = 'Hello!';
$request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);

// Or, if you don't need to pass in a request instance:
$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();
    }
);
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

Mode 6 :( Concurrent request )

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 on all of the requests to complete.
$results = Promise\unwrap($promises);

// You can access each result using the key provided to the unwrap
// function.
echo $results['image']->getHeader('Content-Length');
echo $results['png']->getHeader('Content-Length');
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

Mode 7 :( Concurrent request , Multithreading )

use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

$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, $index) {
        // this is delivered each successful response
    },
    'rejected' => function ($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();
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.

Request parameters

Request format

$client->request(‘ Request method ’,‘URL Address ’,‘ Configuration parameters ’);
     
  • 1.

Query string parameters

$client->request('GET', 'http://httpbin.org', [
    'query' => ['foo' => 'bar']
]);

 Request address  : http://httpbin.org?foo=bar
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Upload data

// Provide the body as a string.
$r = $client->request('POST', 'http://httpbin.org/post', [
    'body' => 'raw data'
]);
     
  • 1.
  • 2.
  • 3.
  • 4.

Upload data JSON Format

$r = $client->request('PUT', 'http://httpbin.org/put', [
    'json' => ['foo' => 'bar']
]);
     
  • 1.
  • 2.
  • 3.

POST Send form fields

$response = $client->request('POST', 'http://httpbin.org/post', [
    'form_params' => [
        'field_name' => 'abc',
        'other_field' => '123',
        'nested_field' => [
            'nested' => 'hello'
        ]
    ]
]);
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

Send form file

$response = $client->request('POST', 'http://httpbin.org/post', [
    'multipart' => [
        [
            'name'     => 'field_name',
            'contents' => 'abc'
        ],
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'other_file',
            'contents' => 'hello',
            'filename' => 'filename.txt',
            'headers'  => [
                'X-Foo' => 'this is an extra header to include'
            ]
        ]
    ]
]);
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

send out Cookies

//  Carry... When sending a request cookies
// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
    'cookies' => $jar
]);

//  All requests carry cookies
// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

Request header

// Set various headers on a request
$client->request('GET', '/get', [
    'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ]
]);
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

Using agents

$client->request('GET', '/', [
    'proxy' => [
        'http'  => 'tcp://localhost:8125', // Use this proxy with "http"
        'https' => 'tcp://localhost:9124', // Use this proxy with "https",
        'no' => ['.mit.edu', 'foo.com']    // Don't use a proxy with these
    ]
]);
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

Redirect

//  Default true, The default maximum number of times is 5 The redirection of 
$res = $client->request('GET', '/redirect/3', ['allow_redirects' => false]);
echo $res->getStatusCode();
     
  • 1.
  • 2.
  • 3.

request timeout

// Timeout if a server does not return a response in 3.14 seconds.
$client->request('GET', '/delay/5', ['timeout' => 3.14]);
// PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException'
     
  • 1.
  • 2.
  • 3.

File store

$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);
     
  • 1.

Use response

$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
    echo "It exists";
}

// Get a header from the response.
echo $response->getHeader('Content-Length');

// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values) . "\r\n";
}
//  Get the content returned by the response 
$contents = $response->getBody()->getContents();
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

 

Multithreading scenario

Scene one : Multithreading downloads files with different link addresses

<?php require_once "vendor/autoload.php"; use GuzzleHttp\Pool; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; $client = new Client(); $requests = [ new Request('GET', 'www.google.com', [], null, 1.1), new Request('GET', 'www.ebay.com', [], null, 1.1), new Request('GET', 'www.cnn.com', [], null, 1.1), new Request('GET', 'www.red.com', [], null, 1.1), ]; $pool = new Pool($client, $requests, [ 'concurrency' => 5, 'fulfilled' => function ($response, $index) { // this is delivered each successful response }, 'rejected' => function ($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();
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

Scene two : Download rule link file

<?php require_once "vendor/autoload.php"; use GuzzleHttp\Pool; use GuzzleHttp\Client; $client = new Client(); $requests = function ($total) use ($client) { for ($i = 0; $i < $total; $i++) { $url = "http://domain.com/picture/{$i}.jpg"; $filepath = "/tmp/{$i}.jpg"; yield function() use ($client, $url, $filepath) { return $client->getAsync($url, [ 'sink' => $filepath ]); }; } }; $pool = new Pool($client, $requests(10), [ 'concurrency' => 5, 'fulfilled' => function ($response, $index) { // this is delivered each successful response }, 'rejected' => function ($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();
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.

Scene three : Upload big files

<?php require_once "vendor/autoload.php"; use GuzzleHttp\Psr7; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; $resource = fopen($pathname, 'r'); $stream = Psr7\stream_for($resource); $client = new Client(); $request = new Request( 'POST', $api, [], new Psr7\MultipartStream( [ [ 'name' => 'bigfile', 'contents' => $stream, ], ] ) ); $response = $client->send($request);
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

Scene 4 : Download big files

<?php require __DIR__ . '/vendor/autoload.php'; use GuzzleHttp\Client; $url = "https://domain.tld/large-file.mp4"; $tmpFile = tempnam(sys_get_temp_dir(), 'guzzle-download'); $client = new Client(array( 'base_uri' => '', 'verify' => false, 'sink' => $tmpFile, 'curl.options' => array( 'CURLOPT_RETURNTRANSFER' => true, 'CURLOPT_FILE' => $handle ) )); $res = $client->get($url); echo $res->getStatusCode() . "\n"; echo $res->getHeaderLine('content-type') . "\n";
     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

treasure

flow   treasure Waiting for everyone to dig

 

copyright notice
author[Ian2012],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210826045949961G.html

Random recommended