简体   繁体   English

确定HTTP响应的大小?

[英]Determine size of HTTP Response?

Is there a way to determine the size of the HTTPServletResponse content? 有没有办法确定HTTPServletResponse内容的大小? I read this get-size-of-http-response-in-java question but sadly where I work I do not have access to CommonsIO :( 我读了这个get-size-of-http-response-in-java问题,但遗憾的是我工作的地方我无法访问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 ... PS我读了erickson的答案但它提到了输入流我想知道正在写出的对象的大小...如果writeObject()方法返回一个表示写入的字节而不是void的数字,那将是非常好的...

If you have access to the response header, you can read the Content-Length . 如果您有权访问响应标头,则可以阅读Content-Length

Here is a example of a 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 检查一下: 标题字段定义

Assuming the use of ObjectOutputStream , build it around a java.io.ByteArrayOutputStream : 假设使用ObjectOutputStream ,围绕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 with 然后你可以发送内容

contentBytes.writeTo(connection.getOutputStream());

where connection is whatever you're getting your OutputStream from. 在哪里connection是你从OutputStream获得的。

Better late than never, right? 迟到总比不到好,对吧?

This seems to be what you're looking for: 似乎是你正在寻找的:

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

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. 在发送之前我仍然想知道它在服务器端是什么,但这是下一个最好的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM