【问题标题】:Apache Web Server Get - File SizeApache Web 服务器获取 - 文件大小
【发布时间】:2015-06-25 01:44:03
【问题描述】:

我想访问本地 Apache Web 服务器及其文件,比如http://foo.com/cats.jpg

我不希望我的客户看到图像,而是接收数据,显示其文件大小和数据传输的持续时间并刷新文件。我怎样才能用 Java HTTP 代码做到这一点?

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://foo.com/cats.jpg");
HttpResponse response = client.execute(request);

// Get the response but don't show the content, just file size and duration of data transfer

感谢您的帮助!

【问题讨论】:

  • 你能用response.getLastHeader("Content-Length").getValue()吗?
  • 这个方法到底是做什么的?我猜它获取文件的大小,但不是数据传输时间? :)
  • 当您执行html get 操作时,它会返回一个响应。该响应包含带有重要信息的标头以及内容(在本例中为 .jpg 文件)。 header可以告诉你长度,mime-type等。如果你需要显示文件长度,你可以用我提到的函数来获得。
  • 太好了!太感谢了!关于如何测量数据传输(或连接)时间的任何想法?
  • 要测量时间,您可以在执行get 操作之前获取当前时间,然后再减去当前时间。使用System.currentTimeMillis(),差异会告诉您操作花费了多少毫秒。

标签: java apache http data-transfer


【解决方案1】:

当您执行html get 操作时,它会返回响应。该响应包含带有重要信息的标头以及内容(在本例中为 .jpg 文件)。 header 可以告诉你长度,mime-type 等。如果你需要显示文件长度,你可以使用

response.getLastHeader("Content-Length").getValue()

要确定数据传输花费了多长时间,只需在要计时的操作之前和之后调用System.currentTimeMillis(),然后减去它们即可知道操作花费了多少毫秒。例如:

long start = System.currentTimeMillis();
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://foo.com/cats.jpg");
HttpResponse response = client.execute(request);
String size = response.getLastHeader("Content-Length").getValue();
long end = System.currentTimeMillis();
System.out.println("It took "+(end-start)+" milliseconds and the file is "+
    size+" bytes long");

【讨论】:

  • 再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2021-08-07
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
相关资源
最近更新 更多