PHP Curl未设置正文参数或内容类型



我目前正试图从微软的Grapgh Rest Api请求Graph令牌,我与邮递员合作得很好,但当我试图通过php curl发送相同的请求时,我会得到

AADSTS900144: The request body must contain the following parameter: 'grant_type'.

收到这个错误后,我在发送curl请求之前检查了它,向我显示既没有设置正文,也没有设置内容类型,因为我将其设置为x-www-form,但它保持为"application/json"。

也许有人知道发生了什么事,可以帮助我。

<!DOCTYPE html>
<html>
<head>
<?php
$data = array('grant_type' => 'client_credentials', 'client_secret' => '****', 'client_id' => '****');
$postdata = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.microsoftonline.com/7390211a-8059-450c-ab26-2f8adac42536/oauth2/token?resource=https://graph.microsoft.com' );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
?>
</head>
<body>
<?php echo $result ?>
</body>
</html>

在curl_getinfo($ch(上打印的结果是:

Array ( [url] => https://login.microsoftonline.com/7390211a-8059-450c-ab26-2f8adac42536/oauth2/token?resource=https://graph.microsoft.com [content_type] => application/json; charset=utf-8 [http_code] => 400 [header_size] => 686 [request_size] => 360 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.187 [namelookup_time] => 0.015 [connect_time] => 0.046 [pretransfer_time] => 0.14 [size_upload] => 139 [size_download] => 503 [speed_download] => 2689 [speed_upload] => 743 [download_content_length] => 503 [upload_content_length] => 139 [starttransfer_time] => 0.187 [redirect_time] => 0 [redirect_url] => [primary_ip] => 40.126.1.166 [certinfo] => Array ( ) [primary_port] => 443 [local_ip] => 192.168.15.231 [local_port] => 61831 )

我在网上找到了一个php片段,它对我来说很有魅力

$data = array('grant_type' => 'client_credentials', 'client_secret' => '****', 'client_id' => '****');
$url = 'https://login.microsoftonline.com/****/oauth2/token?scope=https://graph.microsoft.com/User.ReadWrite.All';
$options = array(
'http' => array(
'header'  => "Content-type: application/x-www-form-urlencodedrn",
'method'  => 'POST',
'content' => http_build_query($data)
)
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }

最新更新