支持异步、并发请求,支持cookies等
php composer.phar require guzzlehttp/guzzle:~6.0
/**
* form表单 post
*/
private function post($uri, $data = [], $headers = [], $base_uri = 'https://demo.com')
{
$client = new Client(["base_uri" => $base_uri]);
try {
$result = $client->request('POST', $uri, [
'headers' => $headers,
'form_params' => $data
]);
$body = $result->getBody();
} catch (ConnectException $e) {
trace($e->getMessage(), 'error');
return false;
} catch (ClientException $e) {
$code = $e->getResponse()->getStatusCode();
$body = $e->getResponse()->getBody();
return json_decode($body, true);
trace($code . $body, 'error');
return false;
} catch (RequestException $e) {
// Catch all 4XX errors
// To catch exactly error 400 use
if ($e->getResponse()->getStatusCode() == '400') {
trace("Got response 400", 'error');
}
// You can check for whatever error status code you need
$code = $e->getResponse()->getStatusCode();
$body = $e->getResponse()->getBody();
trace($code . $body, 'error');
return false;
} catch (\Exception $e) {
// There was another exception.
trace($e->getMessage(), 'error');
return false;
}
return json_decode($body, true);
}
单元测试demo TestCase.php
<?php
namespace tests;
use think\Env;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;
class TestCase extends \think\testing\TestCase
{
protected $baseUrl = '';
protected $headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ',
];
public function __construct()
{
$this->baseUrl = Env::get('test.baseUrl', 'http://demo.com');
$this->headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . Env::get('test.token'),
];
config('database.database', isset($_ENV['DATABASE']) ? $_ENV['DATABASE'] : 'miner_staging');
}
/**
* REST API GET
*/
public function get($uri, $headers = [])
{
$client = new Client(["base_uri" => $this->baseUrl]);
try {
$result = $client->request('GET', $uri, [
'headers' => $headers ? $headers : $this->headers,
]);
$body = $result->getBody();
} catch (ConnectException $e) {
return ['code' => 500, 'msg' => $e->getMessage()];
} catch (ClientException $e) {
echo $e->getResponse()->getStatusCode();
$body = $e->getResponse()->getBody();
return json_decode($body, true);
} catch (RequestException $e) {
// Catch all 4XX errors
// To catch exactly error 400 use
if ($e->getResponse()->getStatusCode() == '400') {
echo "Got response 400";
}
// You can check for whatever error status code you need
echo $e->getResponse()->getStatusCode();
$body = $e->getResponse()->getBody();
return json_decode($body, true);
} catch (\Exception $e) {
// There was another exception.
// There was another exception.
echo $e->getMessage();
return false;
}
return json_decode($body, true);
}
/**
* REST API POST
*/
public function post($uri, $data = [], $headers = [])
{
$client = new Client(["base_uri" => $this->baseUrl]);
try {
$result = $client->request('POST', $uri, [
'headers' => $headers ? $headers : $this->headers,
'json' => $data
]);
$body = $result->getBody();
} catch (ConnectException $e) {
return ['code' => 500, 'msg' => $e->getMessage()];
} catch (ClientException $e) {
echo $e->getResponse()->getStatusCode();
$body = $e->getResponse()->getBody();
return json_decode($body, true);
} catch (RequestException $e) {
// Catch all 4XX errors
// To catch exactly error 400 use
if ($e->getResponse()->getStatusCode() == '400') {
echo "Got response 400";
}
// You can check for whatever error status code you need
echo $e->getResponse()->getStatusCode();
$body = $e->getResponse()->getBody();
return json_decode($body, true);
} catch (\Exception $e) {
// There was another exception.
echo $e->getMessage();
return false;
}
return json_decode($body, true);
}
}
对比curl实现
<?php
namespace App\Tests;
/**
* HTTPClient 类
*
* @package sae
* @author Elmer Zhang
* @version 1.0
*/
class HTTPClient{
/**
* Contains the last HTTP status code returned.
*
* @ignore
*/
public $http_code;
/**
* Contains the last API call.
*
* @ignore
*/
public $url;
/**
* Set up the API root URL.
*
* @ignore
*/
public $host = "https://api.weixin.qq.com/cgi-bin/";
/**
* Set timeout default.
*
* @ignore
*/
public $timeout = 30;
/**
* Set connect timeout.
*
* @ignore
*/
public $connecttimeout = 30;
/**
* Verify SSL Cert.
*
* @ignore
*/
public $ssl_verifypeer = FALSE;
/**
* Respons format.
*
* @ignore
*/
public $format = 'json';
/**
* Decode returned json data.
*
* @ignore
*/
public $decode_json = TRUE;
/**
* Contains the last HTTP headers returned.
*
* @ignore
*/
public $http_info;
/**
* Set the useragnet.
*
* @ignore
*/
public $useragent = 'WeiXin OAuth1 v0.1';
/**
* print the debug info
*
* @ignore
*/
public $debug = FALSE;
/**
* boundary of multipart
* @ignore
*/
public static $boundary = '';
/**
* GET wrappwer for oAuthRequest.
*
* @return mixed
*/
function get($url, $parameters = array()) {
$response = $this->oAuthRequest($url, 'GET', $parameters);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response, true);
}
return $response;
}
/**
* POST wreapper for oAuthRequest.
*
* @return mixed
*/
function post($url, $parameters = array(), $postbody = false) {
$response = $this->oAuthRequest($url, 'POST', $parameters, $postbody );
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response, true);
}
return $response;
}
/**
* Format and sign an OAuth / API request
*
* @return string
* @ignore
*/
function oAuthRequest($url, $method, $parameters, $postbody = false) {
if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
$url = "{$this->host}{$url}";
}
switch ($method) {
case 'GET':
$url = $url . '?' . http_build_query($parameters);
return $this->http($url, 'GET');
default:
$headers = array();
if (!$postbody && (is_array($parameters) || is_object($parameters)) ) {
$body = http_build_query($parameters);
} else {
$body = $postbody;
}
return $this->http($url, $method, $body, $headers);
}
}
/**
* Make an HTTP request
*
* @return string API results
* @ignore
*/
function http($url, $method, $postfields = NULL, $headers = array()) {
$this->http_info = array();
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_ENCODING, "");
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
curl_setopt($ci, CURLOPT_HEADER, FALSE);
switch ($method) {
case 'POST':
curl_setopt($ci, CURLOPT_POST, TRUE);
if (!empty($postfields)) {
curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
$this->postdata = $postfields;
}
break;
case 'DELETE':
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
if (!empty($postfields)) {
$url = "{$url}?{$postfields}";
}
}
if ( isset($this->access_token) && $this->access_token ){
if(strpos($url,"?")>0){
$url.="&access_token=".$this->access_token;
}else{
$url.="?access_token=".$this->access_token;
}
}
if(isset($_SERVER['REMOTE_ADDR'])){
$headers[] = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR'];
}
curl_setopt($ci, CURLOPT_URL, $url );
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );
$response = curl_exec($ci);
$this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
$this->http_info = array_merge($this->http_info, curl_getinfo($ci));
$this->url = $url;
if ($this->debug) {
echo "=====post data======\r\n";
var_dump($postfields);
echo '=====info====='."\r\n";
print_r( curl_getinfo($ci) );
echo '=====$response====='."\r\n";
print_r( $response );
}
curl_close ($ci);
return $response;
}
/**
* Get the header info to store.
*
* @return int
* @ignore
*/
function getHeader($ch, $header) {
$i = strpos($header, ':');
if (!empty($i)) {
$key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
$value = trim(substr($header, $i + 2));
$this->http_header[$key] = $value;
}
return strlen($header);
}
}
参考
https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html
发表评论 登录: