Search code examples
javaiohttpresponse

Determine size of HTTP Response?


Is there a way to determine the size of the HTTPServletResponse content? I read this get-size-of-http-response-in-java question but sadly where I work I do not have access to CommonsIO :(

The response content consists of a single complex object so I have considered writing it out to a temp file and then checking that file. This is not something I want to be doing as a diagnostic while the application is running in production though so want to avoid it if at all possible.

PS I read erickson's answer but it mentioned input streams I want to know the size of the object being written out... Would be really nice if the writeObject() method returned a number representing bytes written instead of void...


Solution

  • I eventually found a way to get what I wanted:

    URLConnection con = servletURL.openConnection();
    BufferedInputStream bif = new BufferedInputStream(con.getInputStream());
    ObjectInputStream input = new ObjectInputStream(bif);
    int avail = bif.available();
    
    System.out.println("Response content size = " + avail);
    

    This allowed me to see the response size on the client. I still would like to know what it is on the server side before it is sent but this was the next best thing.