通过PHP卷曲调用获取数据

时间:2014-10-09 09:13:49

标签: php api rest curl postman

我正在尝试进行PHP Curl Call。该调用适用于POSTMAN,如下所示:

URL Endpoint: https://api.sb.example.com/v1/resource/identifier

Headers: 
Content Type: application/json
Authorization : Bearer AccessTokenValue

HTTP Protocol : GET

此调用返回有效的JSON响应。现在,当我使用PHP执行相同操作时,我无法获得响应。这是我的PHP Curl调用:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sb.example.com/v1/resource/identifier");
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type : application/json',
                                            'Authorization : Bearer AccessTokenValue'
));

$data = curl_exec($ch);
print_r($data);
curl_close($ch);

通过PHP进行的调用给出了错误:

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1

代码的任何想法/建议?

2 个答案:

答案 0 :(得分:0)

请在curl_exec()

之前添加以下所述行
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);                                         
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

答案 1 :(得分:0)

所以我想通了,我在KeyValue对中的头数组中有一个空格。

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type : application/json', ..)

应该是

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',