开发者

Java Servlet and HTTP Response object

开发者 https://www.devze.com 2023-02-16 19:54 出处:网络
Question on HttpResponse object in servlets. Can the contents of a HttpResponse be only read once? If so do I need to user a filter and some form of \"javax.servlet.http.HttpServletResponseWrapper\"

Question on HttpResponse object in servlets. Can the contents of a HttpResponse be only read once?

If so do I need to user a filter and some form of "javax.servlet.http.HttpServletResponseWrapper" in开发者_如何转开发 order to read the content of a HttpResponse object as I need to read its content to retrieve XML/JSON from the response? At the moment Im getting the below exception when I go to read the HttpResponse object.

     Content has been consumed
at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)

Thanks, John


This is not a problem in the server/servlet side. It's a problem in the client side. The servlet doesn't send HttpServletResponse object to the client or something, it just sends a byte stream only once. You just need to read it only once into a reuseable object such as a byte[] or String, depending on the actual content and and then reuse/copy exactly this object in the remnant of the code.

InputStream input = httpResponse.getEntity().getContent();
ByteArrayOutputStream output = new ByteArrayOutputStream(); // Or some file?
IOUtils.copy(input, output);
byte[] content = output.toByteArray();
// Now you can reuse content as many times as you want.


Do you want to read the content of the response or request? Usually we write the content of the response and do not read it, unless you have an special case here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号