使用Guzzle执行HTTP请求
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客户端,功能非常强大。
使用Guzzle执行HTTP请求的更多相关文章
- 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 ...
- 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 ...
- rxjava 调用retrofit执行网络请求的过程
retrofit流程图 -1.RxJava调用Retrofit,从requestGtPushSaeUserInfo()中获得被观察者observable,然后new一个观察者向它订阅 0.从业务中 ...
- Jmeter执行Java请求
Jmeter执行Java请求(QQ交流群:577439379) 一.打开Eclipse,创建一个Java工程 二.拷贝jmeter所依赖的jar包 将jmeter中,\lib\ext目录下的Apach ...
- LInux命令执行http请求
Linux下提供了一些命令可以直接执行http请求,下面举例来介绍几个命令. http // GET请求 http http://127.0.0.1:2379/version http GET htt ...
- JS获取页面数据执行Ajax请求
下面这个例子展示了如何使用js获取页面中元素的值,并且将这些值作为参数执行Ajax请求. $("#submit-task").bind("click", fun ...
- 解决 ASP.NET Chart 控件出错 为 ChartImg.axd 执行子请求时出错
今天在做一个关于MVC的MSChart时,本以为很简单的一个东西,后面把数据什么的都绑定好后,满以为OK了,一运行就报错“ ASP.NET Chart 控件出错 为 ChartImg.axd ...
- 错误: 实例 "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 ...
- CASE函数 sql server——分组查询(方法和思想) ref和out 一般处理程序结合反射技术统一执行客户端请求 遍历查询结果集,update数据 HBuilder设置APP状态栏
CASE函数 作用: 可以将查询结果集的某一列的字段值进行替换 它可以生成一个新列 相当于switch...case和 if..else 使用语法: case 表达式/字段 when 值 then ...
随机推荐
- [20190727NOIP模拟测试9]单(single) 题解(树上dp)
啊啊啊啊啊啊啊啊考场上差一点就A掉了5555 千里之堤溃于蚁穴……鬼知道最后一步那么显然的柿子我为什么没考虑用上…… 观察数据范围可知,出题人期望我们想出一个$O(n)$的做法 当然也有可能是$O(n ...
- 小程序setdata json数据的方法
有如下几种数据格式: sort_condition: { curIndex: ', curArrow: ' } ,//排序界面 date_condition: [ { curIndex: ', cur ...
- thinkphp 相关
路径重写,既模式2 需要.htaccess文件放到index.php同级, http.config文件 中当前项目目录配置 AllowOverride All LoadModule rewrite_ ...
- English-Words with 'ir'
hire thirty thirteen third sir birthday shirt stir circle dirty skirt affirm affirmation affirmable ...
- 用 Flask 来写个轻博客 (28) — 使用 Flask-Assets 压缩 CSS/JS 提升网页加载速度
Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 扩展阅读 Flask-Assets 将 Flask-Assets 应用 ...
- IDEA 创建 Maven web项目注意事项
需要设置 Maven ->Runner->VM options -Dmaven.multiModuleProjectDirectory=$M2_HOME 需要添加一个archetypeCa ...
- UVA12174_Shuffle
Shuffle 大致题意: 你有一个随机播放的播放器,有s首歌,在这s首播放完之前不会重新打乱顺序,现在给出一段只含有1~s的n长度序列,现在问你下次随机排序发生的时间有多少种可能 其实就是问你这个播 ...
- Ubuntu18.10 编译libevent出现错误: creating symbolic link XXXXXX : Operation not supported
今天在VirtualBox虚拟机下的Ubuntu18.10编译libevent源代码时,按照github中使用cmake方式: $ mkdir build && cd build $ ...
- 读取hive文件并将数据导入hbase
package cn.tansun.bd.hbase; import java.io.IOException; import java.net.URI; import java.util.List; ...
- Java必备主流技术流程图,写得非常好!
作者:Jay_huaxiao https://juejin.im/post/5d214639e51d4550bf1ae8df 1.spring的生命周期 Spring作为当前Java最流行.最强大的轻 ...