0

我目前正在尝试让 HttpComponents 发送 HttpRequests 并检索响应。在大多数 URL 上,这都没有问题,但是当我尝试获取 phpBB 论坛的 URL 时,即http://www.forum.animenokami.com客户端需要更多时间,并且 responseEntity 包含不止一次的段落导致损坏.html 文件。

例如,元标记包含六次。由于许多其他 URL 有效,我无法弄清楚我做错了什么。该页面在已知浏览器中正常工作,因此这不是他们方面的问题。

这是我用来发送和接收的代码。

        URI uri1 = new URI("http://www.forum.animenokami.com");
    HttpGet get = new HttpGet(uri1);
    get.setHeader(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:6.0) Gecko/20100101 Firefox/6.0"));
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(get);
    HttpEntity ent = response.getEntity();
    InputStream is = ent.getContent();
    BufferedInputStream bis = new BufferedInputStream(is);
    byte[] tmp = new byte[2048];
    int l;
    String ret = "";
    while ((l = bis.read(tmp)) != -1){
        ret += new String(tmp);
    }

我希望你能帮助我。如果您需要更多信息,我会尽快提供。

4

2 回答 2

4

这段代码完全被破坏了:

String ret = "";
while ((l = bis.read(tmp)) != -1){
    ret += new String(tmp);
}

三件事:

  • 这是在每次迭代时将整个缓冲区转换为字符串,无论读取了多少数据。(我怀疑这就是你的情况实际上出了什么问题。)
  • 它使用默认的平台编码,这几乎不是一个好主意。
  • 它在循环中使用字符串连接,这会导致性能不佳。

幸运的是,您可以使用以下方法轻松避免所有这些EntityUtils

String text = EntityUtils.toString(ent);

这将使用响应中指定的适当字符编码(如果有),否则使用 ISO-8859-1。(如果未指定,还有另一个重载允许您指定要使用的字符编码。)

值得了解您的原始代码有什么问题,而不是仅仅用更好的代码替换它,这样您就不会在其他情况下犯同样的错误。

于 2011-08-27T13:25:54.537 回答
0

它工作正常,但我不明白为什么我只在这个 URL 上多次看到相同的文本。

这将是因为您的客户端在读取套接字时会看到更多不完整的缓冲区。比可能是:

  • 因为从远程站点到您的客户端的路由存在网络带宽瓶颈,
  • 因为远程站点正在进行一些不必要的刷新,或者
  • 其他一些原因。

The point is that your client must pay close attention to the number of bytes read into the buffer by the read call, otherwise it will end up inserting junk. Network streams in particular are prone not filling the buffer.

于 2011-08-27T14:33:52.080 回答