API集成使用PHP curl函数调用不成功,求解


#1

使用API集成时,命令行curl运行都正常,但是在PHP里执行出错。返回
{"result":"failed","message":"无法解析的事件","data":null,"totalCount":0,"code":"3"}
看起来是发送的请求格式还是有问题,求解
代码如下:
`
$url = "http://api.110monitor.com/alert/api/event";
$data = array();
$data['app'] = '3b59c3fd...'; // 申请的key
$data['eventId'] = strval(time());
$data['eventType'] = 'trigger';
$data['alarmName'] = $title;
$data['entityName'] = $entityName;
$data['entityId'] = $entityId;
$data['priority'] = $priority;
$data['alarmContent'] = $content;

$data = json_encode($data);

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HEADER, array(
'Content-type: application/json'

));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$ret = curl_exec($ch);
`


#2

已经搞定

用Wireshark抓包,看PHP发送的数据Content-Type是application/x-www-form-urlencoded。起先以为CURLOPT_POSTFIELDS强行设定的,后来看到是curl_setopt($ch, CURLOPT_HEADER, array(
'Content-type: application/json'

));
错了,应该用CURLOPT_HTTPHEADER。还是自己代码写的有问题


#3

:slight_smile: 解决了就好,后面有问题欢迎来论坛进行提问