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