【问题标题】:PHP cURL JSON APIPHP 卷曲 JSON API
【发布时间】:2015-03-25 01:07:36
【问题描述】:

我的 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。

【问题讨论】:

  • 可能-F 是字段,如在CURLOPT_POSTFIELDS 内发布的必填字段之一?...
  • man curl 会告诉你所有命令行参数是什么......甚至curl --help。不,您没有正确执行此操作。 -F 设置后字段键=值对。你只是发送一个无名的 json 字符串。
  • 我无权访问命令行,因此无法执行 man curl 等操作,但是是的,该手册页很有帮助。你是什​​么意思我正在发送一个无名字符串?抱歉,如果这是基本的,但我正在努力解决。
  • 将json数据作为CURLOPT_POSTFIELDS发送是否不正确?

标签: php json api curl


【解决方案1】:

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

我放了

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

而不是

$str_data = json_encode($data);

它现在似乎可以工作了。

谢谢

【讨论】:

    猜你喜欢
    • 2016-08-12
    • 2011-05-15
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多