您的位置:首页 > 其它

curl发起post,header

2019-06-16 11:01 232 查看
curl发起post,header

function call($postArr,$url,$headerArr) {
//启动一个CURL会话
$ch = curl_init();

// 设置curl允许执行的最长秒数
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');

// 证书
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false) ;

// 获取的信息以文件流的形式返回,而不是直接输出,需要设置,因为默认是0,即返回的数据无法通过变量来接收,而是直接输出了。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//发送一个常规的POST请求。
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);

//要传送的所有数据
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postArr));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);

// 执行操作
$res = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($res == NULL) {
curl_close($ch);
return false;
} else if($code  != "200") {
curl_close($ch);
return false;
}

curl_close($ch);
return $res;
}

调用

$postArr = array(
'accid' => 'qwerty123',
'name'	=> 'raoxiaoya',
'mobile'=> '15919906312'
);

$headers = array(
'AppKey: '.$AppKey,
'Nonce: '.$Nonce,
'CurTime: '.$CurTime,
'CheckSum: '.strtolower(SHA1($AppSecret . $Nonce . $CurTime)),
'Content-Type: application/x-www-form-urlencoded;charset=utf-8'
);

call($postArr,$url,$headerArr);

小结

1、CURLOPT_RETURNTRANSFER
获取的信息以文件流的形式返回,需要设置为1,因为默认是0,即返回的数据无法通过变量来接收,而是直接输出了;

2、CURLOPT_POST
设置为1

3、CURLOPT_POSTFIELDS
post的字段,可以接收字符串(&连接的)或数组。
如果是一维数组的话,可以直接传;如果是超过一维了,则会报错,因此,建议先通过 http_build_query 来转义成字符串再传。

4、http_build_query
(多维)数组->(多维)关联数组->&连接的字符串->urlencode转义
示例:
$data = array('foo', 'bar', 'baz', 'boom', 'milk', 'hypertext_processor');
echo http_build_query($data) . "\n"; // 0=foo&1=bar&2=baz&3=boom&4=milk&5=hypertext_processor

$param = array('foo' => ['bar' => 'cow']);
echo http_build_query($param) . "\n"; // foo%5Bbar%5D=cow  这是什么?我们urldecode一下得到 foo[bar]=cow

一个精简的post请求

function cutl_post($url, $postArr){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postArr));
$res = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($res == NULL) {
curl_close($ch);
return false;
} else if($code  != "200") {
curl_close($ch);
return false;
}

curl_close($ch);
return $res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: