gpt4 book ai didi

java - 使用 DefaultHttpResponseWriter 编写实体

转载 作者:行者123 更新时间:2023-11-29 05:05:46 26 4
gpt4 key购买 nike

使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com