在项目中使用第三方接口时,可以使用封装的工具Guzzle。
Guzzle是PHP的HTTP客户端,用于轻松提交请求并将其集成到我们的WEB服务中。
界面很简单。 构建查询语句、POST请求、下载大文件、使用http cookie、上传JSON数据等。
使用相同的接口发送同步或异步请求。
可以使用PSR-7接口请求、响应和分流,并使用其他兼容的PSR-7类库与Guzzle协同开发。
我们抽象了基本的HTTP传输,使您可以更改环境和其他代码,如到cURL和PHP的流和套接字不是严重依赖关系,也不是块事件循环。
在中间件系统中,可以创建组成客户机的行为。
合成器安装
composerrequireguzzlehttp/guzzle
简单的例子
创建客户端
use GuzzleHttpClient;
$ client=new客户端([
//baseuriisusedwithrelativerequests
' base_uri'='http://httpbin.org ',
//youcansetanynumberofdefaultrequestoptions。
“时间输出”=2.0,
];
发送请求
$ response=$客户端- get (http://http bin.org/get );
$ response=$ client-delete (' http://http bin.org/delete );
$ response=$ client-head (' http://http bin.org/get );
$ response=$ client-options (' http://http bin.org/get ' );
$ response=$客户端- patch (http://http bin.org/patch );
$ response=$客户端- post (http://http bin.org/post );
$ response=$客户端- put (http://http bin.org/put );
可以创建请求,并在准备好后将其发送到客户端。
use GuzzleHttpPsr7Request;
$request=newrequest('put )、' http://httpbin.org/put );
$ response=$ client-send ($ request,['timeout'=2];
异步请求
$ promise=$ client-get async (' http://http bin.org/get ' );
$ promise=$客户端- delete async (http://http bin.org/delete );
$ promise=$ client-head async (' http://http bin.org/get ' );
$ promise=$客户端- options async (http://http bin.org/get );
$ promise=$客户端- patch async (http://http bin.org/patch );
$ promise=$ client-post async (' http://http bin.org/post ' );
$ promise=$ client-put async (' http://http bin.org/put ' );
并发请求
use GuzzleHttpClient;
USEGuzzlehttp(promise;
$ client=new client ([ ' base _ uri '=' http://http bin.org/' ] );
//initiateeachrequestbutdonotblock
$promises=[
' image '=$客户端-获取同步(/image )、
' png '=$客户端- get async (/image/png )、
' JPEG '=$客户端- get async (/image/JPEG )、
' webp '=$客户端-获取同步(/image/webp ) )。
];
//waitonalloftherequeststocomplete。
$results=promise(unwrap ) $promises;
//youcanaccesseachresultusingthekeyprovidedtotheunwrap
//功能。
echo $ results [ ' image ' ]-get header [ ' content-length ' ];
echo $ results [ ' png ' ]-get header (' content-length );
上传数据
//Guzzle为上传数据提供了几种方法。 可以发送包含数据流的请求,也可以将主体请求参数设置为字符串、fopen返回的资源或PSRhttpmessagestream interface的实例。
//Provide the body as a string。
$r=$client-request('post )、' http://httpbin.org/post )、[
' body'='raw data '
];
//Provide an fopen资源。
$body=fopen('/path/to/file ',' r ' );
$r=$client-request('post、' http://httpbin.org/post、['body'=$body] );
//use the stream _ for (功能性tocreateapsr-7 stream )。
$ body=guzzle httpPSR7 stream _ for (' hello!' );
$r=$client-request('post、' http://httpbin.org/post、['body'=$body] );
要上载//JSON数据并设置相应的标头信息,可以使用一种简单的方法: JSON请求参数。
$r=$client-request('put )、' http://httpbin.org/put )、[
' json'=['foo'='bar']
];
.
官方手册
以上是手册采集内容
~谢谢您的夸奖~
授奖