【问题标题】:Passing X-Api-Key through file_get_contents通过 file_get_contents 传递 X-Api-Key
【发布时间】:2021-11-22 13:49:56
【问题描述】:

我正在尝试从流服务器上的 JSON 端点获取数据。我读过我需要通过 X-API-Key 标头传递 API 密钥。但不确定如何执行此操作。

$url = file_get_contents('XXXXX/history');
$data1 = json_decode($url,true);
var_dump($data1);

当从不需要 api 密钥的文件中获取 json 数据时,此代码适用于我。现在如何返回 NULL,因为密钥没有被提交。

有什么想法吗?

【问题讨论】:

标签: php json api


【解决方案1】:

试试这个:

$url = 'XXXXX/history';
$options = array('http' => array(
    'method'  => 'GET',
    'header' => 'Authorization: Bearer '.$yourApiKey
));
$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

【讨论】:

  • 不幸的是它只是返回 NULL
  • 你的api密钥怎么样?
【解决方案2】:

尝试使用 CURL:

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, 'XXXXX/history');
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000); // 3 sec.
curl_setopt($ch, CURLOPT_TIMEOUT, 10000); // 10 sec.
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: ' . $yourApiKey
                ));
$result = curl_exec($ch);
curl_close($ch);


print_r($result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2018-08-13
    • 2019-01-16
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多