Reputation: 27222
Using apache httpcomponents core I have a BasicHttpResponse
with an associated StringEntity
that I'd like to send out through a HttpResponseWriter
of some kind.
I though I could use a DefaultHttpResponseWriter
but looking at its implementation it seems to only write the header data. This makes sense as I'm only receiving the header. I'd like to write out the whole message, entity data included.
Is there a class that will do this as part of the basic core distribution? It doesn't seem like this should be an uncommon use case but I can't find anything.
I'm tempted to just add a writeTo of my own, but that seems hacky. Are there better ways than this?
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();
Upvotes: 1
Views: 160
Reputation: 27548
The only missing bit is selecting an appropriate content codec / delineation strategy
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();
Upvotes: 3