2017-10-12 172 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