1. 程式人生 > >php通過curl請求介面的各種設定

php通過curl請求介面的各種設定

第一:請求頭部方式 為json ,獲取狀態碼

function send_http_json($url,$data)
{
    $ch      = curl_init($url);
    $this_header[] = "content-type:application/json";// json方式
    curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header); 
    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
    $returnData = curl_exec($ch);
    $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE); // 獲取返回來的狀態碼
    return $httpCode;
}

第二 :設定請求方式 、設定頭部token

function send_http_json2($url,$data,$token,$method='POST')
{
    $ch      = curl_init($url);
    $this_header[] = "content-type:application/json";
    $this_header[] = 'Token:'.$token;// 請求的頭部資訊新增token
    curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header); 
    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, 1);
    }elseif($method == 'delete') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');// 定義請求方法
    }
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
    $returnData = curl_exec($ch); 
    return $returnData;
}

第三:使用代理伺服器訪問介面

function https_request($requestUrl)
{
    $type = 'http';
    $cUrl = curl_init();
    curl_setopt($cUrl, CURLOPT_URL, $requestUrl);
    curl_setopt($cUrl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($cUrl, CURLOPT_TIMEOUT, 10);
    curl_setopt($cUrl, CURLOPT_PROXY, '10.0.248.64:3128'); //做代理的ip和埠
    if($type=='https'){ //不使用證書
        curl_setopt($cUrl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($cUrl, CURLOPT_SSL_VERIFYHOST, FALSE);
    }
   $pageContent = curl_exec($cUrl);
   return $pageContent;
}