Guzzle 入门教程

Guzzle入门教程

Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。

  • 接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。
  • 发送同步或异步的请求均使用相同的接口。
  • 使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。
  • 抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。
  • 中间件系统允许你创建构成客户端行为。

安装

Guzzle是一个流行的PHP HTTP客户端库,用于发送HTTP请求并处理响应。以下是一个简单的Guzzle使用示例,包括GET和POST请求:

安装 Guzzle:

composer require guzzlehttp/guzzle

GET 请求示例:

<?php
require 'vendor/autoload.php'; // 引入Composer自动加载文件

use GuzzleHttp\Client;

// 创建一个Guzzle客户端实例
$client = new Client();

// 发送一个GET请求到某个API
$response = $client->request('GET', 'https://api.example.com/data');

// 获取响应的HTTP状态码
$status_code = $response->getStatusCode();
echo "Status Code: " . $status_code . PHP_EOL;

// 获取JSON格式响应体并解码为数组
$json_response = json_decode($response->getBody(), true);
print_r($json_response);

POST 请求示例(带JSON数据):

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

// 创建一个带有JSON内容的POST请求
$data = [
    'key1' => 'value1',
    'key2' => 'value2',
];

$client = new Client();

$options = [
    RequestOptions::HEADERS => [
        'Content-Type' => 'application/json',
    ],
    RequestOptions::JSON => $data,
];

$response = $client->request('POST', 'https://api.example.com/submit', $options);

$status_code = $response->getStatusCode();
echo "Status Code: " . $status_code . PHP_EOL;

// 解析响应体
$json_response = json_decode($response->getBody(), true);
print_r($json_response);

在上述例子中,我们创建了Client对象,并通过调用request()方法来发送HTTP请求。对于POST请求,我们设置了请求头中的Content-Typeapplication/json,并且将要发送的数据作为JSON格式放在选项中。

请根据实际API地址替换 https://api.example.com/datahttps://api.example.com/submit。同时,请确保你对目标API具有适当的访问权限。

Demo

$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();

https://guzzle-cn.readthedocs.io/zh-cn/latest/



欢迎关注公-众-号【TaonyDaily】、留言、评论,一起学习。

公众号

Don’t reinvent the wheel, library code is there to help.

文章来源:刘俊涛的博客


若有帮助到您,欢迎点赞、转发、支持,您的支持是对我坚持最好的肯定(_)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章