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.util.CharsetUtil;
26
27 public class HttpUploadClientHandler extends SimpleChannelUpstreamHandler {
28
29 private boolean readingChunks;
30
31 @Override
32 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
33 if (!readingChunks) {
34 HttpResponse response = (HttpResponse) e.getMessage();
35
36 System.err.println("STATUS: " + response.getStatus());
37 System.err.println("VERSION: " + response.getProtocolVersion());
38
39 if (!response.headers().names().isEmpty()) {
40 for (String name: response.headers().names()) {
41 for (String value: response.headers().getAll(name)) {
42 System.err.println("HEADER: " + name + " = " + value);
43 }
44 }
45 }
46
47 if (response.getStatus().getCode() == 200 && response.isChunked()) {
48 readingChunks = true;
49 System.err.println("CHUNKED CONTENT {");
50 } else {
51 ChannelBuffer content = response.getContent();
52 if (content.readable()) {
53 System.err.println("CONTENT {");
54 System.err.println(content.toString(CharsetUtil.UTF_8));
55 System.err.println("} END OF CONTENT");
56 }
57 }
58 } else {
59 HttpChunk chunk = (HttpChunk) e.getMessage();
60 if (chunk.isLast()) {
61 readingChunks = false;
62 System.err.println("} END OF CHUNKED CONTENT");
63 } else {
64 System.err.println(chunk.getContent().toString(CharsetUtil.UTF_8));
65 }
66 }
67 }
68
69 @Override
70 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
71 e.getCause().printStackTrace();
72 e.getChannel().close();
73 }
74 }