Search code examples
javaapachehttpdata-transfer

Apache Web Server Get - File Size


I would like to access a local Apache Web Server and its files, let's say, http://foo.com/cats.jpg

I don't want my client to see the image, instead, receive the data, show its file size and the duration of data transfer and flush the file. How can I do it with a Java HTTP code?

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

Thank you for the help!


Solution

  • When you perform an html get operation it returns a response. That response contains headers with important information, along with the content (in this case a .jpg file). The header can tell you things like the length, the mime-type, etc. If you need to display the file length, you can use

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

    To determine how long the data transfer took, just call System.currentTimeMillis() before and after the operations you want to time, and subtract them to know how many milliseconds the operations took. For example:

    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");