Netty, how to read chunked HTTP response without using one of the 4.0.0 alpha releases?

I noticed that in the Netty 4.0.0 alpha releases, an HTTP response object has a method to to test for chunking (isChunked()). In The 3.5.7.Final release, only the request object has a method to test for chunking. Using 3.5.7.Final how could I go about reading in a chunked response? Code below that I used for a 4.0.0 alpha test:

@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception {

    try {
        log.trace("Message received");

        if (newMessage) {
            log.trace("New message");
            HttpResponse response = (HttpResponse) event.getMessage();
            log.trace("STATUS: [{}], VERSION [{}]", response.getStatus(), response.getProtocolVersion());

            if (!response.getHeaderNames().isEmpty()) {
                for (String name: response.getHeaderNames()) {
                    for (String value: response.getHeaders(name)) {
                        log.trace("HEADER: [{}] = [{}]", name, value);
                    }
                }
            }
            newMessage = false;
            if (response.isChunked()) {
                requestContentStream = new ByteArrayOutputStream();
                readingChunks = true;
                log.trace("CHUNKED CONTENT {");
                return;
            } else {
                log.trace("Request not chunked");
                writeNonChunkedData(response);
                responseComplete(event);
                return;
            }
        } else if (readingChunks) {
            log.trace("Reading chunks");
            HttpChunk chunk = (HttpChunk) event.getMessage();
            if (chunk.isLast()) {
                log.trace("Read last chunk");
                readingChunks = false;
                writeChunkedData();
                responseComplete(event);
                return;
            } else {
                log.trace("Buffering chunk content to byte buffer");
                requestContentStream.write(chunk.getContent().array());
                return;
            }
        } else {
            log.error("Error handling of MessageEvent, expecting a new message or a chunk from a previous message");
            //setError(context, INTERNAL_SERVER_ERROR);
            super.messageReceived(context, event);
        }
    }catch (Exception ex) {
        log.error("Exception: [{}]", ex);
        //setError(context, INTERNAL_SERVER_ERROR);
        super.messageReceived(context, event);
    }
 }

Answer

HttpResponse.isChunked() also exist in netty 3.5.7. Not sure why you think it doesn’t .. See [1] and [2].

[1] https://github.com/netty/netty/blob/3/src/main/java/org/jboss/netty/handler/codec/http/HttpMessage.java

[2] https://github.com/netty/netty/blob/3/src/main/java/org/jboss/netty/handler/codec/http/HttpResponse.java

Leave a Reply

Your email address will not be published. Required fields are marked *