1. 程式人生 > >PHP Curl請求Https接口

PHP Curl請求Https接口

html code urn operator nec tran ring AR image

在請求http的時候只需要

file_get_contents("http://www.sojson.com/open/api/weather/json.shtml?city=$Position");
就可以了,但是發現這個接口現在變成了https協議了
還用這種方法就會403
首先看看PHP有沒有curl擴展,我是7.2

技術分享圖片

我用的是Laravel社區的封裝好的方法

 public static function curl($url, $params = false, $ispost = 0, $https = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt(
$ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_USERAGENT, ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36‘); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt(
$ch, CURLOPT_RETURNTRANSFER, true); if ($https) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 對認證證書來源的檢查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 從證書中檢查SSL加密算法是否存在 } if ($ispost) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt(
$ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_URL, $url); } else { if ($params) { if (is_array($params)) { $params = http_build_query($params); }
       curl_setopt(
$ch, CURLOPT_URL, $url . ‘?‘ . $params);  // 此處就是參數的列表,給你加了個? } else { curl_setopt($ch, CURLOPT_URL, $url); } } $response = curl_exec($ch); if ($response === FALSE) { //echo "cURL Error: " . curl_error($ch); return false; } $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $httpInfo = array_merge($httpInfo, curl_getinfo($ch)); curl_close($ch); return $response; }



// 發送請求
$result = self::curl(‘網址‘, ‘參數‘, true);
// 收到的數據需要轉化一下
$json = json_decode($result);

我的用法是,應為我調用的是天氣預報的接口
$result= Curl::curl($url,"city=北京");
 

PHP Curl請求Https接口