yii2 httpClient的用法示例:

<?php
/*
* @Purpose : yii2 httpClient 请求示例
* @Author : Chrdai
* @Time : 2018-05-09
* */ use Yii;
use yii\base\Controller;
use yii\helpers\Json;
use yii\httpclient\Client; class TestController extends Controller
{
//use ControllerTrait; /*
* @Perpose 定义接口请求地址
*/
public $url = 'http://192.168.18.100'; /**
* @var Client
*/
public $httpClient = null; /*
* @Perpose 错误信息
*/
public $errMsg = ''; /*
* @Perpose 初始化的时候设置好接口请求地址
*/
public function init()
{
parent::init();
$this->httpClient = new Client([
'baseUrl' => $this->url
]);
} /**
* @Perpose : GET请求示例
* http-client 接口文档:https://www.yiiframework.com/extension/yiisoft/yii2-httpclient/doc/guide/2.0/en/installation
* @return mixed
* http://192.168.18.100/api/test/index
*/
public function actionIndex()
{
$params = 'username=admin&password=21232f297a57a5a743894a0e4a801fc3';
$res = $this->httpClient->get('api/auth/login?' . $params )
->setOptions([
CURLOPT_CONNECTTIMEOUT => 5, // connection timeout
CURLOPT_TIMEOUT => 10, // data receiving timeout
])
->send();
echo "<pre>";
//var_dump($res);
var_dump($res->isOk);
var_dump($res->data);
if($res->isOk && is_array($res->data)){
if($res->data['errno'] == 0){
return Json::encode($res->data['result']['access_token']);
}
}else{
$this->errMsg = $res->data['errmsg'];
throw new \Exception($this->errMsg);
}
return false;
} /**
* @Perpose : POST请求示例
*/
public function actionGetOrder()
{
$data = [
'user_id' => '1',
'dept_id' => '2',
];
$params = Json::encode($data);
$res = $this->httpClient->post('/api/order?access_token=c834472d8193946f6465c9264b9f64d0',$params,['Content-Type'=>'application/json'])
->setOptions([
CURLOPT_CONNECTTIMEOUT => 5, // connection timeout
CURLOPT_TIMEOUT => 10, // data receiving timeout
])
->send();
if ($res->isOk && is_array($res->data)) {
if ($res->data['errno'] == 0) {
return Json::encode($res->data['result']);
} else {
$this->errMsg = $res->data['errmsg'];
throw new \Exception($this->errMsg);
}
}
return false;
} public function actionGetOrder1()
{
$data = [
'user_id' => '1',
'dept_id' => '2',
];
$token['access_token'] = trim($this->actionIndex(),'"') ;
$url = strpos($this->url,'?') ? $this->url . '/api/order&' . http_build_query($token) : $this->url . '/api/just-ari?' . http_build_query($token);
//var_dump($url);die;
$res = $this->httpClient->createRequest()
->setMethod('POST') // 请求方式
->setUrl($url) // 请求地址
->setData($data) //数据传数组
->setHeaders(['Content-Type'=>'application/json']) //header
->setFormat(Client::FORMAT_JSON) //提交的数据的格式
->setOptions([
CURLOPT_CONNECTTIMEOUT => 5, // connection timeout
CURLOPT_TIMEOUT => 10, // data receiving timeout
])
->send();
if ($res->isOk && is_array($res->data)) {
if ($res->data['errno'] == 0) {
return Json::encode($res->data['result']);
} else {
$this->errMsg = $res->data['errmsg'];
throw new \Exception($this->errMsg);
}
}
return false;;
}
}

·

05-06 01:24