先上代码看下问题原因:post方法代码:
/**
* 接口发送数据 POST
* @param String $url 请求的地址
* @param Array $header 自定义的header数据
* @param Array $content POST的数据
* @return String
*/
public function tocurl($url, $header, $content){
$ch = curl_init();
if(substr($url,0,5)=='https'){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
$response = curl_exec($ch);
if($error=curl_error($ch)){
die($error);
}
curl_close($ch);
return $response;
}
//发送json的接口
public function test2(){
$url = 'http://api.openluat.com/mafu/event/device/status';
$header=array(
'Content-Type:application/json',
'Authorization:11111111111111111'
);
$imei = '869300031672938';
$content = array(
"imei"=>$imei
);
$content = json_encode($content);
// print_r($content);exit();
$response = $this->tocurl($url, $header, $content);
$data = json_decode($response, true);
print_r($data);
return $data;
}
这样子的调用接口,一直返回参数错误,后来发现是在content里数据没有json发送过去,解决方法就是在tocurl方法里把http_build_query方法去掉即可。