本文主要是介绍GuzzleHttp的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、背景
作为经常需要使用到的API,项目可以添加GuzzleHttp扩展来使用,方便,快捷,全面;
这次我们项目开发使用的是laravel5.8,那么对于接口数据均是采用GuzzleHttp来获取的,文档有较为全面的使用介绍,本仙女这就只总结自己能用到的哟
二、封装使用
/*** 请求接口,获取e信使用户需要完成的阅读任务* @param string $post 请求方式* @param array $data 请求数据* @param string $sRequUrl 请求接口地址* @return array** @throws GuzzleException*/public function sendRequest($post = 'GET', $sRequUrl, $data = []){if (config('app.env') != 'production') {return false;}//区分请求方式$aParams =[];if($post == 'GET' ){$aParams = ['query'=>$data];}else if($post == 'POST' ){$aParams = ['form_params'=>$data];}try {$httpClient = $httpClient = new Client(['timeout' => 60]);$sHttpRes = $httpClient->request($post, $sRequUrl, $aParams)->getBody()->getContents();return json_decode($sHttpRes, true);} catch (\Exception $exception) {info('调用接口发生错误--------------' . $sRequUrl);info($exception);info('------------------------');}return false;}
这里是一个封装好的方法,但仅仅是对get和post做了处理,接下来是使用步骤的描述;
2.1 Making a Request
首先创建一个GuzzleHttp\ClientInterface 对象,用来发送请求;
use GuzzleHttp\Client;
$httpClient = 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,
]);
因为我这个方法是用户承接不同网站的数据,数据在创建对象的时候并没有初始化一个base_uri,
2.2 Sending Requests
$response = $client->get('http://httpbin.org/get');
$response = $client->post('http://httpbin.org/post');
$client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
等形式,没有参数时,倒是不用操作,但是接口参数是一般都有的,所以当你使用get或者post请求方式的时候就要做一个区分处理了,对于get:参数放在query的数组里面;对于post:参数是放在头部参数form_params数组里的;
2.3 Using Reponses
请求发送以后,就是响应的接收处理啦。
$ body = $ response - > getBody ();
这是获取响应Reponse的整体,获取响应的内容则是$body->getContents();
至此大致的逻辑就已经可以了。
2.4 异步请求的封装
/*** 请求接口,获取e信使用户需要完成的阅读任务* @param string $post 请求方式* @param string $sRequUrl 请求接口地址* @param array $data 请求数据* @return bool*/public function sendAsyncRequest($post = 'GET', $sRequUrl, $data = []){try {$httpClient = new Client(['timeout' => 60]);$httpClient->requestAsync($post, $sRequUrl, ['query' => $data])->then(function (ResponseInterface $res) {info($res->getBody()->getContents());return json_decode($res->getBody()->getContents(), true);},function (RequestException $e) {info('调用接口发生错误--------------');info($e->getMessage());})->wait();} catch (\Exception $exception) {info('调用接口发生错误--------------' . $sRequUrl);info($exception);info('------------------------');}return false;}
这都是本人正在使用的接口,希望分享出来有帮助到你!
三、写在最后
这个用起来还是很方便的,大家可以再深入研究一下,这里是GuzzleHttp文档
这篇关于GuzzleHttp的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!