官方文档:
https://www.yiiframework.com/extension/yiisoft/yii2-httpclient
yii框架发送请求:
1.默认使用StreamTransport
类:fopen( )方式打开资源
$client = new Client();
$response = $client->createRequest()
->setMethod('POST')
->setUrl('https://me.csdn.net/api/relation/create?source=blog')
->setData(['username' => 'justry_deng'])
->setOptions([
'timeout' => 5, // set timeout to 5 seconds for the case server is not responding
])
->send();
$response = $response->getContent();
print_r($response);die;
返回结果:
{"code":400102,"message":"\u7528\u6237\u4e0d\u5b58\u5728","data":""}
2.使用yii\httpclient\CurlTransport
请求资源:CURL方式
2.0熟悉curl配置:
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);//78 在发起连接前等待的时间(秒),如果设置为0,则无限等待。
curl_setopt($ch, CURLOPT_TIMEOUT, 2);//13---设置cURL允许执行的最长秒数。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//19913--将curl_exec()获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($ch, CURLOPT_HEADER, false);//42----启用时会将头文件的信息作为数据流输出
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //禁用后cURL将终止从服务端进行验证,信任任何证书,https需设置---64
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //是否需要验证证书--81
curl_setopt($ch, CURLOPT_POST, 1);//47----启用时会发送一个常规的POST请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);//10015
curl_setopt($ch, CURLOPT_URL,$url);//10002
2.1服务端是https,需要验证证书
yii 2的curl请求默认验证证书,如果你没有设置证书,会报错
HTTP Client Exception – yii\httpclient\Exception
Curl error: #60 - SSL certificate problem: self signed certificate in certificate chain
客户端代码:
2.2无需证书验证:
客户端
代码:
$client = new Client();
$client->setTransport(CurlTransport::class);
$request = $client->createRequest()
->setUrl('http://47.93.**.**/api/dicine/cinema/city-list') //HTTP链接,不需要验证证书
->setOptions([
CURLOPT_TIMEOUT=>'2',
])
->setMethod('POST') //设置请求方式
->addHeaders([
'SecretNum' =>'eruoueoidkja8d0780as',
'Referer' =>'https://blog.csdn.net/justry_deng/article/details/81042379',
'User-Agent'=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
])
->setData([
'userId'=>'123',
'name'=>'张三',
])
->send();
;
print_r($request->getcontent());die;
服务端
代码:
Yii::$app->getResponse()->format='json';
$res['post'] = Yii::$app->getRequest()->post();
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
$res['headers'] = $headers;
return $res;
请求返回结果: