guzzle/guzzle 日常使用

来源:互联网 发布:java bigdecimal取整 编辑:程序博客网 时间:2024/06/14 02:48

Guzzle

Guzzle 是一个 PHP HTTP 客户端,致力于让发送 HTTP 请求以及与 Web 服务进行交互变得简单。
Github:https://github.com/guzzle/guzzle
Composer:https://packagist.org/packages/guzzlehttp/guzzle

发送请求

use GuzzleHttp\Client;$client = new Client([    //跟域名    'base_uri' => 'http://localhost/test',    // 超时    'timeout'  => 2.0,]);$response = $client->get('/get'); //http://localhost/get$response = $client->delete('delete');  //http://localhost/get/delete$response = $client->head('http://localhost/get');$response = $client->options('http://localhost/get');$response = $client->patch('http://localhost/patch');$response = $client->post('http://localhost/post');$response = $client->put('http://localhost/put');

POST

$response = $client->request('POST', 'http://localhost/post', [    'form_params' => [        'username' => 'webben',        'password' => '123456',        'multiple' => [            'row1' => 'hello'        ]    ]]);

响应

# 状态码$code = $response->getStatusCode(); // 200$reason = $response->getReasonPhrase(); // OK# header// 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";}# 响应体$body = $response->getBody();// Implicitly cast the body to a string and echo itecho $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();

自定义header

// Set various headers on a request$client->request('GET', '/get', [    //header    'headers' => [        'User-Agent' => 'testing/1.0',        'Accept'     => 'application/json',        'X-Foo'      => ['Bar', 'Baz']    ],    //下载    'save_to'=> $filename,    //referer    'allow_redirects' => [        'referer'       => '',    ],]);
$client = new \GuzzleHttp\Client();$url = 'https://www.baidu.com/getUserInfo';$jar = new \GuzzleHttp\Cookie\CookieJar();$cookie_domain = 'www.baidu.com';$cookies = [    'BAIDUID'   => '221563C227ADC44DD942FD9E6D577EF2CD',];$cookieJar = $jar->fromArray($cookies, $cookie_domain);$res = $client->request('GET', $url, [       'cookies' => $cookieJar,       // 'debug' => true,]);$body = $res->getBody();

手册地址:http://docs.guzzlephp.org/en/stable/request-options.html#headers