Search code examples
javaandroidapache-httpclient-4.xandroidhttpclient

Measure HTTP response's exact size in Java's HttpResponse


When using a HttpResponse from the Apache HttpClient in Java or Android, I'd like to get the response's exact size for logging/analysis somehow.

Is this possible?

  • response.getEntity().getContentLength() doesn't need to be set by the server (e.g. for chunked responses) so it is not reliable
  • response.getEntity().getContent().available() usually returns 0 as noted in the documentation for InputStream

So is there any alternative? Specifically, I'm using either a normal InputStream or a GZIPInputStream and want the raw data's size (that has been received from the server) for comparison.


Solution

  • Using String.length() always seems to be imprecise, even more so when processing binary GZIP content. But that's probably charset/encoding issues, right?

    As an alternative, I tried to get the length from the InputStream directly:

    /**
     * Measures the content length using the given InputStream
     * 
     * Usage: inputStream = printResponseLength(inputStream);
     * 
     * @param is the InputStream to measure the content length for
     * @return a copy of the InputStream for further reading
     * @throws Exception if the stream cannot be read
     */
    private InputStream printResponseLength(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
    
        System.out.println("Content-Length: "+baos.toByteArray().length);
    
        return new ByteArrayInputStream(baos.toByteArray());
    }
    

    Can someone confirm if this method is correct? At least for me, it seems to print exactly the same content lengths as the developer consoles in Firefox/Chrome.