Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。Guzzle提供了简单的接口,构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。

安装

使用Composer安装:

composer require guzzlehttp/guzzle

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

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

然后执行composer update

Guzzle基本使用

发送请求

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']
]);

使用响应

获取状态码:

$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK

判断头部信息:

if ($response->hasHeader('Content-Length')) {
echo "It exists";
}

获取返回的头部信息:

echo $response->getHeader('Content-Length');

// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}

使用getBody方法可以获取响应的主体部分(body),主体可以当成一个字符串或流对象使用

$body = $response->getBody();

可以将返回体转换成字符串或者直接以字符串形式读取:

$stringBody = (string) $body;
$content = $body->getContents();

上传文件

有时我们需要将文件传送到另一个web服务上去,可以使用post文件流形式将文件数据传送到指定web目录。

$filename = 'a.jpg';
$data = fopen($filename, 'r');
$res = $client->request('POST', 'http://localhost:9999/upload.php', ['body' => $data]);
$body = $res->getBody();
print_r($body->getContents());

接收上传文件的upload.php可以这样写:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = file_get_contents('php://input');
$file = file_put_contents('b.jpg', $data);
if (FALSE === $file) {
echo '上传成功';
} else {
echo '上传失败';
}
}

提交表单

发送application/x-www-form-urlencoded POST请求需要你传入form_params 数组参数,数组内指定POST的字段。

$res = $client->request('POST', 'http://localhost:9999/form.php', [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
$body = $res->getBody();
print_r((string)$body);

在接收端form.php使用$_POST即可获取上传的表单数据。

提交JSON数据

有时候我们在于API接口交互的时候需要将数据以特定的json格式传给api,可以这样写:

$res = $client->request('POST', 'http://localhost:9999/json.php', [
'json' => ['foo' => 'bar']
]); $body = $res->getBody();
print_r((string)$body);

接收端json.php使用file_get_contents('php://input')可获得提交的json数据。

使用Guzzle还可以发送异步请求以及并发请求,具体使用方法可参照Guzzle官方文档

其实我们在一些特殊场景下可以使用Swoole的协程特性实现异步的http客户端,功能非常强大。

https://www.helloweba.net/php/596.html

使用Guzzle执行HTTP请求的更多相关文章

  1. python3.x执行post请求时报错“POST data should be bytes or an iterable of bytes...”的解决方法

    使用python3.5.1执行post请求时,一直报错"POST data should be bytes or an iterable of bytes. It cannot be of ...

  2. Error: 实例 "ddd" 执行所请求操作失败,实例处于错误状态。: 请稍后再试 [错误: Exceeded maximum number of retries. Exhausted all hosts available for retrying build failures for instance 6f60bc06-fcb6-4758-a46f-22120ca35a71.].

    Error: 实例 "ddd" 执行所请求操作失败,实例处于错误状态.: 请稍后再试 [错误: Exceeded maximum number of retries. Exhaus ...

  3. rxjava 调用retrofit执行网络请求的过程

    retrofit流程图 -1.RxJava调用Retrofit,从requestGtPushSaeUserInfo()中获得被观察者observable,然后new一个观察者向它订阅   0.从业务中 ...

  4. Jmeter执行Java请求

    Jmeter执行Java请求(QQ交流群:577439379) 一.打开Eclipse,创建一个Java工程 二.拷贝jmeter所依赖的jar包 将jmeter中,\lib\ext目录下的Apach ...

  5. LInux命令执行http请求

    Linux下提供了一些命令可以直接执行http请求,下面举例来介绍几个命令. http // GET请求 http http://127.0.0.1:2379/version http GET htt ...

  6. JS获取页面数据执行Ajax请求

    下面这个例子展示了如何使用js获取页面中元素的值,并且将这些值作为参数执行Ajax请求. $("#submit-task").bind("click", fun ...

  7. 解决 ASP.NET Chart 控件出错 为 ChartImg.axd 执行子请求时出错

        今天在做一个关于MVC的MSChart时,本以为很简单的一个东西,后面把数据什么的都绑定好后,满以为OK了,一运行就报错“ ASP.NET Chart 控件出错 为 ChartImg.axd ...

  8. 错误: 实例 "ahwater-linux-core" 执行所请求操作失败,实例处于错误状态。: 请稍后再试 [错误: Exceeded maximum number of retries. Exceeded max scheduling attempts 3 for instance 7c1609c9-9d0f-4836-85b3-cefd45f942a7. Last exception: [u

    错误: 实例 "ahwater-linux-core" 执行所请求操作失败,实例处于错误状态.: 请稍后再试 [错误: Exceeded maximum number of ret ...

  9. CASE函数 sql server——分组查询(方法和思想) ref和out 一般处理程序结合反射技术统一执行客户端请求 遍历查询结果集,update数据 HBuilder设置APP状态栏

    CASE函数   作用: 可以将查询结果集的某一列的字段值进行替换 它可以生成一个新列 相当于switch...case和 if..else 使用语法: case 表达式/字段 when 值 then ...

随机推荐

  1. APPium连接真机输入框中输入的内容与代码中不一致

    今天解决了上一个问题,又碰到了一个新的问题. 问题:连接真机输入框中输入的内容与代码中不一致. 描述: 想实现登录页面输入用户名和密码自动登录,可是在输入用户名和密码的框中输入的内容总是与代码中的不一 ...

  2. nRF51822学习笔记 之 blinky_example

    使用的开发板是nRF51822 AK II,爱板网做活动买的. 开发资料可以去这里下载:链接: http://pan.baidu.com/s/1f8pD8 密码: 741y

  3. 测开之路四十八:Django之重定向与cookie

    基础配置与上一篇一致 404错误 定义一个error页面 <!DOCTYPE html><html lang="en"><head> <m ...

  4. fiddler接口知识

    1. 访问接口时经常会出现乱码的情况,需要fiddler解码操作 2.域名过滤

  5. IDEA compile successfully many errors still occur

    Compile and install successfully with maven in IDEA, but error prompt still popup. Your local enviro ...

  6. SSH工具

    SSH是什么:SSH是一种网络协议,用于计算机之间的加密登录   应用:用来连接远程服务器   适用人员:需要操作服务器的程序员,linux管理员等   需要的基础知识: http://www.ee. ...

  7. Mysql 事务相关

    MySQL介绍 什么是MySQL? ​ MySQL 是一种关系型数据库,在Java企业级开发中非常常用,因为 MySQL 是开源免费的,并且方便扩展.阿里巴巴数据库系统也大量用到了 MySQL,因此它 ...

  8. 最大公因数数gcd模板

    首先蒟蒻是在大佬的博客里学习的代码,代码风格多有相似之处,大佬博客https://www.cnblogs.com/lMonster81/p/10433902.html 最大公因数那,顾名思义就是两个数 ...

  9. springboot themaleaf 各种报错

    1.访问themaleaf页面报错 Whitelabel Error Page This application has no explicit mapping for /error, so you ...

  10. nohup及crontab定时任务

    一.关于nohup: 1.假设有一 tash.sh 启动是:nohup /home/spex/bin_prodDemo/task.sh &                         一定 ...