使用PHP卷曲显示错误

使用PHP卷曲显示错误

问题描述:

我使用以下代码来请求来自一个IdentityServer,它使用OpenID协议令牌连接至OpenID:使用PHP卷曲显示错误

$curl = curl_init('https://remoteserver.com/connect/token'); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
$code = $_GET['code']; // The code from the previous request 
$redirect_uri = 'http://mycalldomain.com/test.php'; 

curl_setopt($curl, CURLOPT_POSTFIELDS, array(
    'redirect_uri' => $redirect_uri, 
    'grant_type' => 'authorization_code' 
)); 

curl_setopt($curl, CURLOPT_USERPWD, 
    "MYCLIENTID" . ":" . 
    "MYCLIENTSECRET"); 

$auth = curl_exec($curl); 
print '$auth = ';print_r($auth); // to see the error 
$secret = json_decode($auth); 
$access_key = $secret->access_token; 

是outputing以下错误:

$auth = {"ErrorMessage":"Unsupported Mediatype"} 

有人可以指导这个吗?

你应该提供一个Content-Type HTTP头,你要发布的东西资源接受,加入这样的事情:

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

这将使JSON(!作为一个例子),和你的输出数据(CURLOPT_POSTFIELDS)必须与您选择的内容类型相对应。

目前,内容类型是 “多/表单数据”,按照该PHP documentation

If value is an array, the Content-Type header will be set to multipart/form-data.

如果你想使用的内容类型“应用程序/ x-WWW的形式,进行了urlencoded “,那么除了将其设置为Content-Type之外,您还必须以该格式提供CURLOPT_POSTFIELDS。作为一个Web开发语言,PHP具有这种格式的编码阵列内置功能http_build_query

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
    'redirect_uri' => $redirect_uri, 
    'grant_type' => 'authorization_code' 
))); 
+0

我已经设置了,但仍返回相同的错误。从进一步的调查,它似乎不应该在json中 - http://openid.net/specs/openid-connect-core-1_0.html#TokenRequest –

+0

你能帮我重新格式化我的代码,不知道如何我可以发送以下类型:应用程序/ x-www-form-urlencoded –

+0

我编辑答案也有一个例子。通常,在执行POST时,应始终确保不仅仅是预期的Content-Type,而且还要确保POST数据的格式。许多库将具有默认值,因此代码中的格式可能不明显如果没有明确设置。 – Ilmari