1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.http.upload;
17
18 import org.jboss.netty.buffer.ChannelBuffer;
19 import org.jboss.netty.channel.ChannelHandlerContext;
20 import org.jboss.netty.channel.ExceptionEvent;
21 import org.jboss.netty.channel.MessageEvent;
22 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
23 import org.jboss.netty.handler.codec.http.HttpChunk;
24 import org.jboss.netty.handler.codec.http.HttpResponse;
25 import org.jboss.netty.logging.InternalLogger;
26 import org.jboss.netty.logging.InternalLoggerFactory;
27 import org.jboss.netty.util.CharsetUtil;
28
29 public class HttpUploadClientHandler extends SimpleChannelUpstreamHandler {
30
31 private static final InternalLogger logger =
32 InternalLoggerFactory.getInstance(HttpUploadClientHandler.class);
33
34 private boolean readingChunks;
35
36 @Override
37 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
38 if (!readingChunks) {
39 HttpResponse response = (HttpResponse) e.getMessage();
40
41 logger.info("STATUS: " + response.getStatus());
42 logger.info("VERSION: " + response.getProtocolVersion());
43
44 if (!response.getHeaderNames().isEmpty()) {
45 for (String name: response.getHeaderNames()) {
46 for (String value: response.getHeaders(name)) {
47 logger.info("HEADER: " + name + " = " + value);
48 }
49 }
50 }
51
52 if (response.getStatus().getCode() == 200 && response.isChunked()) {
53 readingChunks = true;
54 logger.info("CHUNKED CONTENT {");
55 } else {
56 ChannelBuffer content = response.getContent();
57 if (content.readable()) {
58 logger.info("CONTENT {");
59 logger.info(content.toString(CharsetUtil.UTF_8));
60 logger.info("} END OF CONTENT");
61 }
62 }
63 } else {
64 HttpChunk chunk = (HttpChunk) e.getMessage();
65 if (chunk.isLast()) {
66 readingChunks = false;
67 logger.info("} END OF CHUNKED CONTENT");
68 } else {
69 logger.info(chunk.getContent().toString(CharsetUtil.UTF_8));
70 }
71 }
72 }
73
74 @Override
75 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
76 throws Exception {
77 e.getCause().printStackTrace();
78 e.getChannel().close();
79 }
80 }