作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 apache httpcomponents 核心,我有一个 BasicHttpResponse
和一个关联的 StringEntity
,我想通过某种 HttpResponseWriter
发送它.
虽然我可以使用 DefaultHttpResponseWriter
但查看它的实现似乎只写入 header 数据。这是有道理的,因为我只收到标题。我想写出整个消息,包括实体数据。
作为基本核心发行版的一部分,是否有一个类可以做到这一点?这似乎不是一个不常见的用例,但我找不到任何东西。
我很想添加一个我自己的 writeTo,但这看起来很老套。还有比这更好的方法吗?
logger.info("Sending response");
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
SessionOutputBufferImpl sob = new SessionOutputBufferImpl(metrics, 1024);
sob.bind(_os);//writes to this buffer go to the output stream/socket
DefaultHttpResponseWriter responseWriter =
new DefaultHttpResponseWriter(sob);
responseWriter.write(resp);
sob.flush();
if (null != resp.getEntity()) {
resp.getEntity().writeTo(_os);
}
sob.flush();
最佳答案
唯一缺少的一点是选择合适的内容编解码器/描述策略
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
SessionOutputBufferImpl sob = new SessionOutputBufferImpl(metrics, 1024);
sob.bind(_os);//writes to this buffer go to the output stream/socket
DefaultHttpResponseWriter responseWriter = new DefaultHttpResponseWriter(sob);
responseWriter.write(resp);
StrictContentLengthStrategy contentLengthStrategy = new StrictContentLengthStrategy();
long len = contentLengthStrategy.determineLength(resp);
OutputStream outputStream;
if (len == ContentLengthStrategy.CHUNKED) {
outputStream = new ChunkedOutputStream(2048, sob);
} else if (len == ContentLengthStrategy.IDENTITY) {
outputStream = new IdentityOutputStream(sob);
} else {
outputStream = new ContentLengthOutputStream(sob, len);
}
if (null != resp.getEntity()) {
resp.getEntity().writeTo(outputStream);
}
// Must be closed, especially when using chunk coding
// in order to generate a closing chunk
outputStream.close();
sob.flush();
关于java - 使用 DefaultHttpResponseWriter 编写实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30400907/
使用 apache httpcomponents 核心,我有一个 BasicHttpResponse 和一个关联的 StringEntity,我想通过某种 HttpResponseWriter 发送它
我是一名优秀的程序员,十分优秀!