guzzle组件的简单使用

06-24 18:27 266 0 1 已编辑

文档: https://guzzle-cn.readthedocs.io/zh_CN/latest/
下载: composer require guzzlehttp/guzzle

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;
use Exception;

// 创建客户端
$client = new Client([
    'base_uri' => 'http://httpbin.org',    // 域名
    'timeout' => $this->timeout            // 超时时间(s)
]);

// Basic Auth账号密码
$auth = ['username', 'password'];

// 设置header
$headers = ['X-CSRF-TOKEN' => '5c12e535-683b-4335-a988-af97fc58beb2']

// 设置cookie
$jar = new CookieJar();
$cookies = ['SESSION' => 'ZmQxN2NlZjgtOGYxYi00MTEzLWJlZTItOTBmZjJlZWE4MGE5'];
$cookiesJar = $jar->fromArray($cookies, 'www.baidu.com');      // 此处的域名不带http或https

// GET请求参数
$params = [
    'query' => ['name' => 'example'],
    'headers' => $headers,
    'auth' => $auth,
    'cookies' => $cookiesJar,
    'proxy' => '127.0.0.1:8888'     // 使用fiddler抓包可设置此项
];

// POST请求参数
$params = [
    'form_params' => ['name' => 'example'],
    'headers' => $headers,
    'auth' => $auth,
    'cookies' => $cookiesJar,
    'proxy' => '127.0.0.1:8888'
];

// 发起同步请求
try {
    $response = $client->request('GET', 'foo/bar', $params);
    $responseHeaders = $response->getHeaders();               // 响应头
    $responseData = $response->getBody()->getContents();      // 响应体
} catch (RequestException $e) {
    throw new Exception(sprintf('请求异常:%s', $e->getMessage()));
}

// 发起异步请求
$promise = $client->requestAsync('GET', 'foo/bar', $params);
$response = $promise->then(
    function (ResponseInterface $res) {
        return $res->getBody()->getContents();
    },
    function (RequestException $e) {
        throw new Exception(sprintf('请求异常:%s', $e->getMessage()));
    }
)->wait();
1 人点赞
Up骚年
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论