2013-03-19 43 views
0

我需要這些頭通入$context變量,我試圖使用把值到一個數組,然後將其通入stream_context_create()功能,但我GET HTTP從file_getcontents功能傳遞報頭插入file_get_contents()函數用於JSON請求

警告
$prod_id = 4322; 
$tnxRef = "RT45635276GHF76783AC"; 
$mackey = "ADECNH576748GH638NHJ7393MKDSFE73903673"; 
$agent = $_SERVER['HTTP_USER_AGENT']; 
$hash = hash('SHA512', $prod_id.$txnRef.$mackey); 

$headers = array(
    'http'=>(
     'method'=>'GET', 
     'header'=>'Content: type=application/json \r\n'. 
      '$agent \r\n'. 
      '$hash' 
     ) 
    ) 
stream_context_create($headers) 

$url_returns = file_get_contents("https://test_server.com/test_paydirect/api/v1/gettransaction.json?productid=$prod_id&transactionreference=$txnRef&amount=$amount", false, $context); 

$json = json_decode($url_returns, true); 

錯誤:

[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request`

那是錯誤我得到的,可以請人一個明確的例子幫助。

+1

OPS,[主要來源](http://stackoverflow.com/questions/15497253/passing-headers-into-file-get-contents)不存在! – 2016-01-22 01:03:29

+0

頁面找不到重複的鏈接... – urban 2016-05-03 19:57:37

回答

2

你的代碼有幾個錯誤。

服務器返回400 Bad Request,因爲你的代碼會導致這種不正確的HTTP請求:

GET /test_paydirect/api/v1/gettransaction.json?productid=4322&transactionreference=RT45635276GHF76783AC&amount= HTTP/1.1 
Host: test_server.com 
Content: type=application/json 
$agent 
$hash 

的錯誤是:

  1. 變量表達式不是單引號內評估
  2. $amount是未在您的代碼示例中設置
  3. 標題爲Content-Type:而不是Content: type=
  4. 所有頭(代理,哈希)都必須有其相應的名稱

下面是一個例子應該工作:

$context = stream_context_create(array(
    'http' => array(
    'method' => 'GET', 
    'agent' => $agent, 
    'header' => "Content-Type: type=application/json\r\n" 
     . "X-Api-Signature: $hash" 
    ) 
) 
); 

請注意:X-Api-Signature僅僅是一個例子 - 它取決於您使用的API如何命名API密鑰標頭以及如何計算哈希值。您應該在API文檔中找到這些信息!

+0

感謝您的響應,這就是我現在$ options = array( 'http'=> array( 'header'=>「Content-Type:application/json 」 '的UserAgent'=> $劑, '散'=> $哈希 ) ),但仍然沒有得到正確的響應 – 2013-03-19 12:18:55

+0

這一點,他們希望得到什麼https://test_server.com/test_paydirect/api /v1/gettransaction.json?productid=$prod_id&transactionreference=$txnRef&amount=$amount HTTP/1.1 UserAgent:Mozilla/blah等等等等(blah)Hash:myhash – 2013-03-19 12:21:48

+0

@ user1872101:1.等級名稱是User-Agent。此外,還有一個獨立的流上下文選項,我在我的例子中使用。就像它一樣使用它! 2.我確定這是因爲你的'Hash'標題。去閱讀你的API的文檔或張貼在這裏,讓人們能夠真正幫助你。 – Kaii 2013-03-19 12:22:21