curl发送json格式数据  php的curl⽅法详细的见官⽅⼿册。
<?php
$params = array(
'par1' => 'a',
'par2' => 11,
);
$header = array("Content-type: application/json");// 注意header头,格式k:v
$arrParams = json_encode($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arrParams);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);// curl函数执⾏的超时时间(包括连接到返回结束)秒单位curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);// 连接上的时长秒单位
curl_setopt($ch, CURLOPT_URL, $url);
$ret = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);// 对⽅服务器返回http code
curl_close($ch);
// deal $ret
值得注意的是,json_encode()
重试的curl⽅法:
<?php
function callCurl($url, $arrParams, $format, $timeout = 15, $retry = 3){
$ch = curl_init();
if('json' === $format){// header
$arrParams = json_encode($arrParams);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));        }
curl_setopt($ch, CURLOPT_POST, true);
phpjson格式化输出curl_setopt($ch, CURLOPT_POSTFIELDS, $arrParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_URL, $url);
$ret = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
while($http_status != 200 && $retry--){
$ret = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
//记录请求⽇志
$arrLog = array(
'url' => $url,
'arrParams' => $arrParams,
'http_status' => $http_status,
'curl_error' => curl_error($ch),
'retry' => $retry,
'result' => $ret,
);
// 记录log
curl_close($ch);
$result = json_decode($ret, true);
return$result;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。