curl post请求body体内传参数

2023-03-14,,

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($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
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);
 
}

 
 
 
 
 
 

curl post请求body体内参数的相关教程结束。

《curl post请求body体内传参数.doc》

下载本文的Word格式文档,以方便收藏与打印。