Determine the size of the HTTP response?

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

The content of the response consists of one complex object, so I decided to write it to the temp file and then check this file. This is not what I want to do as a diagnostic while the application is running during production, although I really want to avoid it, if at all possible.

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

+4
source share
5 answers

In the end, I 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 size of the response on the client. I would still like to know that this is server side before it is sent, but this was the next best.

-3
source

If you have access to the response header, you can read the Content-Length .

Here is an example response header:

 (Status-Line):HTTP/1.1 200 OK Connection:Keep-Alive Date:Fri, 25 Mar 2011 16:26:56 GMT Content-Length:728 

Check this out: Header field definitions

+10
source

This seems to be what you are looking for:

 DataOutputStream dos = new DataOutputStream(response.getOutputStream()); ... int len = dos.size(); 
0
source

Assuming using an ObjectOutputStream , build it around java.io.ByteArrayOutputStream :

 ByteArrayOutputStream contentBytes = new ByteArrayOutputStream(); ObjectOutputStream objectOut = new ObjectOutputStream(contentBytes); objectOut.writeObject(content); int contentLength = contentBytes.size(); 

And then you can send the content using

 contentBytes.writeTo(connection.getOutputStream()); 

where connection is what you get from OutputStream .

Better late than never, right?

0
source

Add a network sniffer:

 var client = new OkHttpClient.Builder().Protocols(protocols) .AddNetworkInterceptor(NetworkInterceptor) .Build(); 

Then in the interceptor:

  private Response NetworkInterceptor(IInterceptorChain chain) { var request = chain.Request(); var response = chain.Proceed(builder.Build()); // print size Console.WriteLine(response.Headers().Size().ToString()); return response ; } 
0
source

Source: https://habr.com/ru/post/1345251/


All Articles