PHP cURL JSON API


PHP cURL JSON API

我的API文档说我需要输入以下cURL。

卷曲

 -H "Accept: application/json"
 -F grant_type=consumer_credentials 
 -F consumer_key=ABCDEFGHIJKLMN
 -F consumer_secret=123456789
 https://sandbox.apps.****.com/api/AccessToken 

我不知道如何处理 -F 位(也不知道 -F 代表什么!所以我把它们作为 JSON 发布数据放入。

我假设 -H 是标题?

作为起点,我有这个:

$data = array(
  "grant_type" => "consumer_credentials",
  "consumer_key" => "ABCDEFGHIJKLMN",
  "consumer_secret" => "123456789"
);
$str_data = json_encode($data);
$url_send ="https://sandbox.apps.****.com/api/AccessToken";
function sendPostData($url, $post){
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));  
  $result = curl_exec($ch);
  curl_close($ch); 
  return $result;
}
echo " " . sendPostData($url_send, $str_data);

但我得到的只是一个页面,说发生了错误。它应该返回带有登录数据的 JSON。

正如 Marc 所说,我是通过 json 而不是普通字段数据发送的。

我投入了

foreach($data as $key=>$value) { $str_data .= $key.'='.$value.'&'; }
rtrim($str_data, '&');

而不是

$str_data = json_encode($data);

它现在似乎正在工作。

谢谢