curl post請求body體內傳參數


1. 傳參格式 json

function post_http($array='',$url)
{
$ch = curl_init();
$header = array('Content-Type: application/json; charset=utf-8','Accept: application/json','secretKey:xxxxxxxx','signKey:xxxxxxxxxxx12');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//https
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 2);
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
 
// post數據
curl_setopt($ch, CURLOPT_POST, 1);
// post設置頭
// curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8080');//設置代理服務器 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// post的變量
$arr = json_encode($array,);
 
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
if (curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
//打印獲得的數據
return json_decode($result,true);
 
}
 
 
2. body體字符串式 表單傳參 數組
 
function post_http($url)
{
 
//方法1 自己拼接
$body = "key=val&key1=val2"; 
 
//方法 2
//或用  $data = ['key' => 'val', 'key1' => 'val1'] ;$body = http_build_query($data) ;構建返回一個 URL 編碼后的字符串
 
$ch curl_init();
curl_setopt($chCURLOPT_URL, $url); 
curl_setopt($chCURLOPT_POST,true);
curl_setopt($chCURLOPT_RETURNTRANSFER1);
 
curl_setopt($chCURLOPT_POSTFIELDS$body);
curl_setopt($chCURLOPT_TIMEOUT30);
$result curl_exec($ch);
if (curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
//打印獲得的數據
return json_decode($result,true);
 
}
 
 
 
 
 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM