Search code examples
javafooterchunked-encodingapache-httpcomponents

How do I get chunked footers from a response on a connection that uses ThreadSafeClientConnManager?


I'm using a connection created by ThreadSafeClientConnManager (Apache httpcomponents 4.1.1). The response is chunked (which I expect), as is determined by response.getEntity().isChunked()

However, there is no way to get the footers/trailers (which are necessary for our application). Since the response was chunked, I would expect the entity contents to be of type ChunkedInputStream, however the default request director and executor classes used by the client wrap the original response entity (which, from looking at the httpcomponents source would have been a ChunkedInputStream) in a BasicManagedEntity.

In short, I am no longer able to get the footers/trailers off of the response, as BasicManagedEntity does not make the underlying entity available for use. Does anyone know how to work around this?

For reference, see:

  • org.apache.http.impl.client.DefaultRequestDirector.java, lines 523-525
  • org.apache.http.impl.entity.EntityDeserializer.java, lines 93-96

Solution

  • One can use an HTTP response interceptor in order to access to the chunked content stream and response footers.

    httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
    
    public void process(
            final HttpResponse response,
            final HttpContext context) throws HttpException, IOException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            if (instream instanceof ChunkedInputStream) {
                Header[] footers = ((ChunkedInputStream) instream).getFooters();
            }
        }
    }
    

    });