【问题标题】:passing headers into file_get_contents() for a json request将标头传递给 file_get_contents() 以获取 json 请求
【发布时间】:2013-03-08 01:47:33
【问题描述】:

我需要将这些标头传递到 $context 变量中,我尝试使用将值放入数组中,然后将其传递到 stream_context_create() 函数中,但我从 file_getcontents 函数中收到 http 警告

$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]:打开流失败:HTTP 请求失败! HTTP/1.1 400 错误请求`

这就是我得到的错误,有人可以帮忙举一个明确的例子吗?

【问题讨论】:

标签: php json http-headers httpwebrequest file-get-contents


【解决方案1】:

您的代码中有几个错误。

服务器返回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: application/json\r\n"
        . "X-Api-Signature: $hash"
    )
  )
);

请注意: X-Api-Signature 只是一个示例 - 它取决于您使用的 API 如何命名 API 密钥标头以及如何计算哈希值。您应该在 API 的文档中找到这些信息!

【讨论】:

  • 感谢您的回复,这就是我现在所拥有的 $options = array( 'http'=>array( 'header'=>"Content-Type: application/json", 'UserAgent'= >$agent, 'Hash'=>$hash ) ) 但仍然没有得到正确的响应
  • 这是他们想要得到的test_server.com/test_paydirect/api/v1/… HTTP/1.1 UserAgent:Mozilla/blah blah blah(blah) 哈希:myhash
  • @user1872101: 1. 标题名称是User-Agent。此外,还有一个单独的流上下文选项,我在我的示例中使用了它。照原样使用它! 2. 我确定这是因为您的Hash 标头。去阅读您的 API 文档或将它们发布在此处,以便人们能够真正为您提供帮助。
  • $amount 是从会话传递过来的,所以被覆盖了
猜你喜欢
  • 2016-04-21
  • 2013-11-23
  • 2015-06-09
  • 1970-01-01
  • 2021-08-30
  • 2012-11-17
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多