【问题标题】:Invalid json format using this api when using curl php使用 curl php 时使用此 api 的 json 格式无效
【发布时间】:2016-11-16 07:01:14
【问题描述】:

这是我的 json 数据

$data = array(
"api_key"=>"xxxx",  
"email_details"=> array( "fromname"=>"test",  
"subject"=>"Registration",   
"from"=>"xxx@xxx.com",   
"content"=>"test"), 
"recipients"=>["xxx@gmail.com"]
);

生成 json 数据:

$str_data = json_encode($data);

它给出了以下 json 格式:

{"api_key":"xxxx",
"email_details":{"fromname":"test","subject":"Registration","from":"xxx@xxx.com","content":"test"},
"recipients":["xxx@gmail.com"]}

是合法的json格式 从此网址验证 http://jsonlint.com/

来自我尝试运行 API 的邮递员:

https://api.xxx.com/xxx/json?data={"api_key":"xxxx","email_details":   {"fromname":"xxx","subject":"Registration","from":"xxx@xxx.com","content":"test" },"recipients":["xxx@gmail.com"]}

收到成功消息

当我试图从 php 代码运行这个 api 时:

$url_email="https://api.xxx.com/xxx/json?data=";

$chh = curl_init();
curl_setopt($chh, CURLOPT_URL,$url_email);
curl_setopt($chh, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($chh, CURLOPT_POSTFIELDS, $str_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
   'Content-Type: application/json',                                                                                
   'Content-Length: ' . strlen($str_data))                                                                       
);  
curl_setopt($chh, CURLOPT_RETURNTRANSFER, true);
curl_exec($chh);
curl_close($chh);

我没有得到 o/p 收到错误消息:

{"message":"ERROR","errorcode": "100" ,"errormessage":"Invalid JSON format used in API Call.Hence failed."}

这里有什么问题?

【问题讨论】:

  • 当您尝试使用邮递员时,是 POST 还是 GET 请求?
  • 你的API需要json格式吗?
  • @MagnusEriksson 它是 POST 方法

标签: php json api curl


【解决方案1】:

我想应该是:

$url_email="https://api.xxx.com/xxx/json";  // no `data` here
$chh = curl_init();
curl_setopt($chh, CURLOPT_URL, $url_email);
curl_setopt($chh, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($chh, CURLOPT_POSTFIELDS, 'data=' . $str_data); // `data` moved here

【讨论】:

  • 仍然收到错误消息 {"message":"ERROR","errorcode": "100" ,"errormessage":"Invalid JSON format used in API Call.Hence failed."}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 2019-12-31
  • 2011-11-07
  • 1970-01-01
相关资源
最近更新 更多