代码之家  ›  专栏  ›  技术社区  ›  er4z0r

获取Java中HTTP响应的大小

  •  5
  • er4z0r  · 技术社区  · 15 年前

    我现在做的是:

       HttpURLConnection con = (HttpURLConnection) feedurl.openConnection();
    

    int feedsize=con.getContentLength();

    问题是,内容legnth并不总是设置好的。例如,当服务器使用transfer encoding=chunked时,我得到一个值-1。

    我愿意 需要这个来显示进度信息。我只需要知道完成后发送给我的数据的大小。

    背景:我需要这些信息,因为我想将其与使用gzip编码发送的响应大小进行比较。

    2 回复  |  直到 14 年前
        1
  •  8
  •   Jim Downing    15 年前

    我会使用 commons-io CountingInputStream

    public long countContent(URL feedurl) {
      CountingInputStream counter = null;
      try {
         HttpURLConnection con = (HttpURLConnection) feedurl.openConnection();
         counter = new CountingInputStream(con.getInputStream());
         String output = IOUtils.toString(counter);
         return counter.getByteCount();
      } catch (IOException ex) {
         throw new RuntimeException(ex);
      } finally {
         IOUtils.closeQuietly(counter);
      }
    }
    
        2
  •  2
  •   erickson    15 年前

    你可以延长 FilterInputStream ,覆盖 read() , read(byte[],int,int) skip 方法,以便在调用 super 窗体中,它们使用读取的字节数更新计数器。

    URLConnection 使用其中一个,并使用包装器代替原始流。完成后,可以查询包装器的计数器。

    其他(“手动”)方法是使用诸如YSlow之类的工具在浏览器中收集统计数据,或使用Wireshark检查网络流量。

    推荐文章