Netty,如何在不使用4.0.0 alpha版本之一的情况下阅读分块HTTP响应?

时间:2012-09-11 19:06:10

标签: java netty

我注意到在Netty 4.0.0 alpha版本中,HTTP响应对象有一个方法来测试分块(isChunked())。在3.5.7.Final版本中,只有请求对象有一个方法来测试分块。使用3.5.7.Final我怎么能在一个分块响应中阅读?我用于4.0.0 alpha测试的代码:

@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);
    }
 }

1 个答案:

答案 0 :(得分:1)