duanfan5012 2019-07-22 08:32
浏览 78
已采纳

没有得到预期的PHP cURL响应

I have the following PHP code:

<?php
$data = array("client_id" => "sipgate-app-web", "grant_type" => "password", "username" => "my_username", "password" => "my_password");
$data_string = json_encode($data);

$ch = curl_init('https://api.sipgate.com/login/sipgate-apps/protocol/openid-connect/token');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json'
));

$result = curl_exec($ch);

echo $result;
?>

Unfortunately, I'm not getting the expected response. The response I'm receiving is:

{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}

When using an online cURL tool like https://onlinecurl.com with the same data (URL, header, data) as in my cURL PHP code, I'm getting the right response. This means, there's something wrong with my PHP code. I'm not getting any error in the PHP error log.

The manual says I have to use the following cURL code:

 curl \
--request POST \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Accept: application/json' \
--data-urlencode "client_id=sipgate-app-web" \
--data-urlencode "grant_type=password" \
--data-urlencode "username=my_username" \
--data-urlencode "password=my_password" \
https://api.sipgate.com/login/sipgate-apps/protocol/openid-connect/token

Since I'm new to cURL, after googling a lot, I have no idea what I'm doing wrong.

Can anybody help me?

EDIT: You can test my PHP code above as it is. You should get the following response, if the code is working:

{"error":"invalid_grant","error_description":"Invalid user credentials"}

  • 写回答

2条回答 默认 最新

  • dongya1228 2019-07-22 08:49
    关注

    As per the manual, your request needs to have the Content-Type of application/x-www-form-urlencoded which looks like this:

    key1=value1&key2=value2
    

    Thus you need to convert your array into such a string either manually or with http_build_query, like so:

    $data_string = http_build_query( $data );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料