无法使用PHP中的Curl发布到API

时间:2017-09-04 09:38:03

标签: php curl

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

“HTTP / 1.1 400 Bad Request Content-Type:application / json Date:Mon,04 Sep 2017 05:40:40 GMT Server:Apigee Router Content-Length:231 Connection: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);

1 个答案:

答案 0 :(得分:0)

看起来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 );