【问题标题】:curl with authentication header token - GET - PHPcurl 带有身份验证标头令牌 - GET - PHP
【发布时间】:2017-01-06 00:09:55
【问题描述】:

我有一个令牌($token 中保存的字符串),我需要使用 curl 从在线服务检索响应 (JSON)。

API 需要 GET。

$crl = curl_init();

$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: OAuth '.$token;

curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
$url = "ENDPOINT"; 
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPGET, 1);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$rest = curl_exec($crl);

curl_close($crl);

var_dump($rest);

转储 $rest 给了我:

 bool(false)

我基于以上thread

【问题讨论】:

  • echo curl_error($crl) 说什么?
  • 错误:未设置 URL!
  • 这很奇怪 - URL 是在 $url 中设置的
  • 你有一个真实的网址,而不仅仅是ENDPOINT这个词,对吧?
  • 是的,需要在标头中传递令牌才能输出 JSON 响应的真实 URL。我只是在帖子中写了 ENDPOINT,因为 URL 不公开。

标签: php curl get


【解决方案1】:

您正在混合变量名称,即。 $crl$ch,把它清理干净,应该没问题,或者至少你应该得到除了 false 之外的其他东西。

我建议你也可以在php.ini 中添加enable error_reporting,在开发过程中你会很容易在你的代码中发现这样的错误。

如果有帮助,这就是我在运行您的代码时在本地得到的:

PHP Notice:  Undefined variable: ch in /home/sebastianforsberg/env/test.php on line 13
PHP Warning:  curl_setopt() expects parameter 1 to be resource, null given in /home/sebastianforsberg/env/test.php on line 13
PHP Notice:  Undefined variable: ch in /home/sebastianforsberg/env/test.php on line 14
PHP Warning:  curl_setopt() expects parameter 1 to be resource, null given in /home/sebastianforsberg/env/test.php on line 14
PHP Notice:  Undefined variable: ch in /home/sebastianforsberg/env/test.php on line 16
PHP Warning:  curl_setopt() expects parameter 1 to be resource, null given in /home/sebastianforsberg/env/test.php on line 16
bool(false)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2020-09-11
    • 2012-10-22
    • 1970-01-01
    • 2018-11-20
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多