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条)

报告相同问题?

悬赏问题

  • ¥15 SAP HANA SQL Script 。SUM OVER 怎么加where
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥60 为什么使用python对地震数据进行umap降维后,数据成图会出现不连续的现象
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败