Guzzle 使用文档

本文介绍了Guzzle,一个遵循PSR-7标准的PHPHTTP客户端,支持异步和并发请求。文中通过示例展示了如何发起GET和POST请求,包括不同类型的POST数据提交,以及如何处理并发请求、使用Cookie和代理。同时,文章还提及了错误处理,如解决cURL证书信任问题的方法。
摘要由CSDN通过智能技术生成

一、简介

Guzzle 是一个知名度很高的 HTTP 客户端库,有以下特性:

  1. 支持异步请求
  2. 支持并发请求
  3. 遵循PSR-7标准
  4. 不依赖 curl 扩展

二、安装 

// 安装指定版本
composer require guzzlehttp/guzzle:7.7.0

// 安装最新版本
composer require guzzlehttp/guzzle

三、使用方式 

  1. 发起 Get 请求
use GuzzleHttp\Client as guzzleClient;

$guzzleClient = new guzzleClient([
    'timeout' => 2.0
]);

// 同步请求方式
$response = $guzzleClient->get(
    'http://api.org/get', 
    [
        'headers' => ['User-Agent' => 'Guzzle'], 
        'http_errors' => false
    ]
);
$code = $response->getStatusCode();
$body = $response->getBody();
$content = $body->getContents();

// 异步请求方式
$promise = $guzzleClient->getAsync('http://api.org/get');
$promise->then(
    function (ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);

2. 发起 Post 请求

use GuzzleHttp\Client as guzzleClient;

$guzzleClient = new guzzleClient([
    'timeout' => 2.0
]);

// 原始类型
$response = $guzzleClient->post('http://api.org/post', [
    'body' => 'raw data'
]);

// json 类型 application/json
$response = $guzzleClient->post('http://api.org/post', [
    'json' => ['name' => 'admin']
]);

// 表单类型 application/x-www-form-urlencoded
$response = $guzzleClient->post('http://api.org/post', [
    'form_params' => [
        'username' => 'abc',
        'password' => '123'
    ]
]);

// 上传文件 multipart/form-data
$response = $guzzleClient->post('http://api.org/post', [
    'multipart' => [
        [
            'name'     => 'user',
            'contents' => 'admin'
        ],
        [
            'name'     => 'file',
            'contents' => fopen('/path/to/file', 'r')
        ],
    ]
]);

$code = $response->getStatusCode();
$body = $response->getBody();
$content = $body->getContents();
// $content = $response->getBody()->getContents();

 3. 并发请求

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

require 'vendor/autoload.php';

$client = new Client();

$requests = function () {
    $urls = [
        'https://ip.taobao.com/ipSearch?ipAddr=1.2.3.4',
        'https://www.baidu.com',
        'https://www.taobao.com',
    ];
    foreach ($urls as $u) {
        yield new Request('GET', $u);
    }
};

$pool = new Pool($client, $requests(), [
    'concurrency' => 3,
    'fulfilled' => function ($response, $index) {
        // 请求成功
        $content = $response->getBody()->getContents();
        switch ($index) {
            case 0:
                echo "淘宝IP: ", $content, "\n";
                break;
            case 1:
                echo "百度首页: ", $content, "\n";
                break;
            case 2:
                echo "淘宝首页: ", $content, "\n";
                break;
            default:
                # code...
                break;
        }
    },
    'rejected' => function ($reason, $index) {
        // 请求失败
    },
]);

$promise = $pool->promise();

$promise->wait();

 4. 使用 Cookie

$client = new \GuzzleHttp\Client(['cookies' => true]);
$response = $client->request('GET', 'http://httpbin.org/cookies');

5. 使用代理

// Win 
set HTTP_PROXY=http://127.0.0.1:1080
set HTTPS_PROXY=http://127.0.0.1:1080

// Linux 
export HTTP_PROXY=http://127.0.0.1:1080
export HTTPS_PROXY=http://127.0.0.1:1080

use GuzzleHttp\Client as guzzleClient;

$guzzleClient = new guzzleClient();
$response = $guzzleClient->get('http://api.org/get');
$content = $response->getBody()->getContents();

// $client->request('GET', '/', ['proxy' => 'tcp://localhost:8125']);


6. 错误处理 。GuzzleHttp请求第三方https接口报错

错误提示:
     cURL error 60: Peer's certificate issuer has been marked as not trusted by the user. (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

 解决方法

  1. $client = new \GuzzleHttp\Client(['verify' => false]);

  2. $client->setDefaultOption('verify', false);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值