file_get_contents()没有“Http”来访问外部网址

时间:2015-07-10 21:25:41

标签: php

我正在尝试访问外部网址(API)

echo file_get_contents("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=4798");

但是,我想要在没有“Http://”的情况下请求此URL - 这会导致它运行得更慢,(不确定为什么)。如果我从参数中删除http://,则无法找到该文件(可以理解)

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

@ jack-hardcastle,基于您的问题下面的评论:尝试增加超时
我尝试在我的计算机上加载Chrome中提供的网址,加载一段时间后,它显示可能是正确的响应。

以下是增加file_get_contents()的HTTP超时的方法:

<?php

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 16.0 // seconds
    )
));

$contents = file_get_contents('http://...', FALSE, $ctx);

// do something with $contents

我还试图找出runescape服务可能检查的缺少的标头;因此,我写了一个简单的脚本,针对GET发送一个简单的httpbin.org请求:

$ ./test
{
  "headers": {
    "Host": "httpbin.org"
  }
}

$ cat test
#!/usr/bin/env php
<?php

die(file_get_contents('http://httpbin.org/headers'));

惊喜:file_get_contents()发送的唯一标题是Host。因此,runescape服务中可能缺少标题中的任何内容。