模拟json方式post提交,设置超时毫秒响应


function http_json($url, $data = NULL, $json = false)

{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if (!empty($data)) {
if($json && is_array($data)){
$data = json_encode( $data );
}
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 300);//
curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);//
if($json){ //发送JSON数据
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json; charset=utf-8',
'Content-Length:' . strlen($data))
);
}
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($curl);
$errorno = curl_errno($curl);

if ($errorno) {
return array('errorno' => false, 'errmsg' => $errorno,'code'=>500);
}
curl_close($curl);
return json_decode($res, true);

}

模拟json方式get提交,设置超时毫秒响应

function http_get($url,$data)
{

$data_json = json_encode($data);
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 300);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 500);

$response  = curl_exec($ch);

curl_close($ch);
return $response;    //返回json对象

}