Java 将 ServletOutputStream 读取为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9656295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading ServletOutputStream to String
提问by Vojtěch
I am trying to read the result of FreemarkerView rendering:
我正在尝试读取 FreemarkerView 渲染的结果:
View view = viewResolver.resolveViewName(viewName, locale);
view.render(model, request, mockResponse);
To read the result, I have created mockResponse
, which encapsulates the HttpServletResponse:
为了读取结果,我创建了mockResponse
,它封装了 HttpServletResponse:
public class HttpServletResponseEx extends HttpServletResponseWrapper {
ServletOutputStream outputStream;
public HttpServletResponseEx(HttpServletResponse response) throws IOException {
super(response);
outputStream = new ServletOutputStreamEx();
}
@Override
public ServletOutputStream getOutputStream() {
return outputStream;
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"));
}
}
And also my ServletOutputStream, which builds the String using StringBuilder:
还有我的 ServletOutputStream,它使用 StringBuilder 构建字符串:
public class ServletOutputStreamEx extends ServletOutputStream {
StringBuilder stringBuilder;
public ServletOutputStreamEx() {
this.stringBuilder = new StringBuilder();
}
@Override
public void write(int b) throws IOException {
}
@Override
public void write(byte b[], int off, int len) throws IOException {
stringBuilder.append(new String(b, "UTF-8"));
}
@Override
public String toString() {
return stringBuilder.toString();
}
}
With those I am able to easily read the response with method ServletOutputStreamEx.toString
.
有了这些,我就可以轻松地使用 method 读取响应ServletOutputStreamEx.toString
。
My problem is that the write method is not called in correct order and in the end the final String is mixed and not in correct order. This is probably caused by concurrency in Freemarker, but I have no idea how to fix it.
我的问题是 write 方法没有以正确的顺序调用,最后最终的 String 是混合的,并且顺序不正确。这可能是由 Freemarker 中的并发引起的,但我不知道如何解决它。
采纳答案by Vojtěch
Thanks for the responses: the write(int b)
was not implemented, because it is never called. The problem in the end is the byte array, which also contains the previous String. So the String needs to be created as String(b, off, len, "UTF-8")
.
感谢您的答复:write(int b)
未实施,因为它从未被调用。最后的问题是字节数组,它也包含了之前的字符串。因此需要将字符串创建为String(b, off, len, "UTF-8")
.