Categories
php

php guzzle 发送http 请求

docs https://docs.guzzlephp.org/

install

composer require guzzlehttp/guzzle

sync get

$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'

async get

$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});

$promise->wait();

post

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://api.github.com/repos/guzzle/guzzle',
 [
   'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ],
    //'query' => ['foo' => 'bar']  //query params
    //'body' => 'foo'   // plain string BODY
    /* 'form_params' => [   //  application/x-www-form-urlencoded
        'foo' => 'bar',
        'baz' => ['hi', 'there!']
    ]*/
    //'json' => ['foo' => 'bar']]  //json body  application/json

    /*'multipart' => [    multipart    multipart/form-data
        [
            'name'     => 'foo',
            'contents' => 'data',
            'headers'  => ['X-Baz' => 'bar']
        ],
        [
            'name'     => 'baz',
            'contents' => Psr7\Utils::tryFopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'qux',
            'contents' => Psr7\Utils::tryFopen('/path/to/file', 'r'),
            'filename' => 'custom_filename.txt'
        ],
    ]*/


 ],
 
);

echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'

Leave a Reply