2017-10-12 65 views
0

我尝试进行经过身份验证的HTTP GET请求,但收到401 HTTP错误。我相信签名是对的。因此,我认为问题出现在第18行的多个标题中,但不幸的是我找不到确切的问题。PHP file_get_contents给出了HTTP代码401未授权

警告:file_get_contents(http://test.com/path):无法打开流:HTTP请求失败! HTTP/1.1 401 /home/host/path.php未经授权在线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); 
} 
?> 

回答

1

您对行格式错误18 您使用逗号来单独报头,而不是你应该将它们连接起来作为一个字符串:

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

Thanks!现在完美运作。 – Remco