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 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果