PHP file_get_contents 给出 HTTP 代码 401 Unauthorized

PHP file_get_contents gives HTTP code 401 Unauthorized

我尝试发出经过身份验证的 HTTP GET 请求,但收到 401 HTTP 错误。我确信签名是正确的。因此,我认为问题出在第 18 行的多个 headers 中。但不幸的是我找不到确切的问题。

Warning: file_get_contents(http://test.com/path): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in /home/host/path.php on line 22

<?php
$apiKey = '1';
$apiSecret = '2';

$verb = 'GET';

$path = '/path';
$nonce = '1';
$data = '';

$signature = hash_hmac('sha256', $verb . $path . $nonce . $data, $apiSecret);

$url="http://test.com/path"; 

$opts = [
    "http" => [
        "method" => $verb,
        "header" => "api-nonce: ".$nonce. "\r\n", "api-key: " .$apiKey. "\r\n", "api-signature: " . $signature
    ]
];
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);

if($json){
    $data = @json_decode($json, TRUE);

    print_r($data);
}
?>

您在第 18 行的格式有误。 您使用逗号分隔 [=13th=],而应该将它们连接成一个字符串:

"header" => "api-nonce: ".$nonce. "\r\n" . "api-key: " .$apiKey. "\r\n" . "api-signature: " . $signature . "\r\n"