guzzlehttp/guzzle发送请求说明

composer require guzzlehttp/guzzle


Guzzle是一个PHP HTTP客户端,可以轻松发送HTTP请求,并且可以轻松集成Web服务。

用于构建查询字符串,POST请求,流式传输大型上传,流式传输大型下载,使用HTTP cookie,上传JSON数据等的简单界面...
可以使用相同的接口发送同步和异步请求。
为请求,响应和流使用PSR-7接口。这使您可以与Guzzle一起使用其他PSR-7兼容库。
抽象出底层的HTTP传输,允许您编写环境和传输不可知的代码; 即不依赖于cURL,PHP流,套接字或非阻塞事件循环。
中间件系统允许您增强和编写客户端行为。

编辑项目的composer.json文件,添加Guzzle作为依赖

{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}

Guzzle基本使用

  • 发送请求
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
 
// 发送一个异步请求
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();
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,
]);
 
$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');

设置查询字符串

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

或使用 query 请求参数来声明查询字符串参数:

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

设置POST表单
传入 form_params 数组参数

$response = $client->request('POST', 'http://httpbin.org/post', [
  'form_params' => [
  'field_name' => 'abc',
  'other_field' => '123',
  'nested_field' => [
  'nested' => '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 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();

 

posted @ 2022-04-25 14:22  知子  阅读(2266)  评论(0编辑  收藏  举报