yii2 本地使用httpclient擴展中的內置類CurlTransport發送curl失敗

官方文檔:
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;

請求返回結果:
在這裏插入圖片描述

發佈了20 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章