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.http2.HttpChunk;
24 import org.jboss.netty.handler.codec.http2.HttpResponse;
25 import org.jboss.netty.util.CharsetUtil;
26
27
28
29
30
31
32
33
34
35 public class HttpResponseHandler extends SimpleChannelUpstreamHandler {
36
37 private volatile boolean readingChunks;
38
39 @Override
40 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
41 if (!readingChunks) {
42 HttpResponse response = (HttpResponse) e.getMessage();
43
44 System.out.println("STATUS: " + response.getStatus());
45 System.out.println("VERSION: " + response.getProtocolVersion());
46 System.out.println();
47
48 if (!response.getHeaderNames().isEmpty()) {
49 for (String name: response.getHeaderNames()) {
50 for (String value: response.getHeaders(name)) {
51 System.out.println("HEADER: " + name + " = " + value);
52 }
53 }
54 System.out.println();
55 }
56
57 if (response.getStatus().getCode() == 200 && response.isChunked()) {
58 readingChunks = true;
59 System.out.println("CHUNKED CONTENT {");
60 } else {
61 ChannelBuffer content = response.getContent();
62 if (content.readable()) {
63 System.out.println("CONTENT {");
64 System.out.println(content.toString(CharsetUtil.UTF_8));
65 System.out.println("} END OF CONTENT");
66 }
67 }
68 } else {
69 HttpChunk chunk = (HttpChunk) e.getMessage();
70 if (chunk.isLast()) {
71 readingChunks = false;
72 System.out.println("} END OF CHUNKED CONTENT");
73 } else {
74 System.out.print(chunk.getContent().toString(CharsetUtil.UTF_8));
75 System.out.flush();
76 }
77 }
78 }
79
80 @Override
81 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
82 throws Exception {
83 e.getCause().printStackTrace();
84 e.getChannel().close();
85 }
86 }