请求API Token时出现unsupported_grant_type错误,求排查原因
问题
我尝试通过某API获取Token,以下是我的PHP代码:
$login = 'TES001'; $password = 'AA758'; $url = "thetestapisite.com/Ticket/v1/Auth/Token"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); $postData = array( 'grant_type'=> 'password', 'username'=> $login, 'password'=> $password, ); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Ocp-Apim-Subscription-Key: theworkingkey")); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, TRUE); var_dump($response);
根据API文档要求,grant_type需设为password,请求头Content-Type为application/x-www-form-urlencoded,但运行代码后返回如下错误:
array(1) { ["error"]=> string(22) "unsupported_grant_type" }
请问我哪里操作出错了?
解决方法
问题出在POST参数的传递方式上:当你给CURLOPT_POSTFIELDS传入数组时,PHP会自动覆盖你设置的Content-Type,将其改为multipart/form-data,导致API无法正确解析grant_type参数,因此返回unsupported_grant_type错误。
解决方式很简单,用http_build_query()函数将数组转换为URL编码的字符串,这样就能满足application/x-www-form-urlencoded的要求:
$postData = http_build_query(array( 'grant_type'=> 'password', 'username'=> $login, 'password'=> $password, ));
修改后的完整代码如下:
$login = 'TES001'; $password = 'AA758'; $url = "thetestapisite.com/Ticket/v1/Auth/Token"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); $postData = http_build_query(array( 'grant_type'=> 'password', 'username'=> $login, 'password'=> $password, )); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Ocp-Apim-Subscription-Key: theworkingkey")); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, TRUE); var_dump($response);
额外提醒:检查你的请求URL是否包含http://或https://前缀,缺少前缀可能导致curl无法正常发起请求。
内容的提问来源于stack exchange,提问作者LiveEn
相关产品推荐
相关产品推荐

