【问题标题】:cannot post to API using Curl in PHP无法在 PHP 中使用 Curl 发布到 API
【发布时间】:2018-02-12 12:38:49
【问题描述】:

我正在使用下面的代码使用 curl 发布到 API,但是遇到了问题/错误

“HTTP/1.1 400 错误请求内容类型:application/json 日期:星期一,2017 年 9 月 4 日 05:40:40 GMT 服务器:Apigee 路由器内容长度:231 连接:keep-alive {"developerMessage ":"请求中不存在所需的参数 client_id,client_secret,grant_type","userMessage":"","errorCode":"AUTH-008","more info":""} "

它说有些参数不存在,而我已经提供了下面代码中所需的所有参数

$url ="mysite.com/authentication/v1/gettoken?client_id=T9hq3zS1CedgVb1mAYECM&client_secret=03hRRTz&grant_type=authorization_code&code=vWnbF8G3UhvMe66-R37lM117LcxjeBLsFwEeLBAy&redirect_uri=mysite.com/testing.php";

$header = array("content-type: application/x-www-form-urlencoded");
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');

echo $retValue = curl_exec($ch);
echo '<br><br>';

//$response = json_decode(curl_exec($ch));
//$ee       = curl_getinfo($ch);
//print_r($ee);

print_r($retValue);

【问题讨论】:

  • 根据 API 消息,您缺少一些凭据。 API 应该在哪里读取凭证?您是否尝试在请求标头中发送这些内容?

标签: php curl


【解决方案1】:

看起来 API 正在等待一个 JSON 字符串,所以试试这个:

$headers = array ( "Content-Type: application/json" );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );

而且由于您使用的是 POST,因此您可能应该发送一些东西:

$json = '{
    "fields": {
        "customfield": [
            "100"
        ]
    }
}';
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $json );

如果需要认证:

$username = "test";
$password = "test";
curl_setopt ( $ch, CURLOPT_USERPWD, $username . ":" . $password );

【讨论】:

  • 上述解决方案均无效。这就是我想要做的。我在developer.autodesk.com 使用 autodesk.com 创建了一个应用程序。我正在尝试使用他们的 3 腿身份验证登录来验证我的应用程序,如下面的链接 developer.autodesk.com/en/docs/oauth/v2/tutorials/… 所示。第一步涉及在表单代码中获取令牌,第二步涉及在 curl 中传递它以验证用户身份,这就是问题所在
  • 可能是这样的:curl_setopt($ch, CURLOPT_URL, "https://developer.api.autodesk.com/authentication/v1/gettoken"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "client_id=obQDn8P0GanGFQha4ngKKVWcxwyvFAGE&amp;client_secret=eUruM8HRyc7BAQ1e&amp;grant_type=authorization_code&amp;code=wroM1vFA4E-Aj241-quh_LVjm7UldawnNgYEHQ8I&amp;redirect_uri=http://sampleapp.com/oauth/callback"); curl_setopt($ch, CURLOPT_POST, 1); $headers = array(); $headers[] = "Content-Type: application/x-www-form-urlencoded"; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
相关资源
最近更新 更多