我注意到在 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);
}
}