1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.http.upload;
17
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.channel.SimpleChannelInboundHandler;
20 import io.netty.handler.codec.http.HttpContent;
21 import io.netty.handler.codec.http.HttpUtil;
22 import io.netty.handler.codec.http.HttpObject;
23 import io.netty.handler.codec.http.HttpResponse;
24 import io.netty.handler.codec.http.LastHttpContent;
25 import io.netty.util.CharsetUtil;
26
27
28
29
30 public class HttpUploadClientHandler extends SimpleChannelInboundHandler<HttpObject> {
31
32 private boolean readingChunks;
33
34 @Override
35 public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
36 if (msg instanceof HttpResponse) {
37 HttpResponse response = (HttpResponse) msg;
38
39 System.err.println("STATUS: " + response.status());
40 System.err.println("VERSION: " + response.protocolVersion());
41
42 if (!response.headers().isEmpty()) {
43 for (CharSequence name : response.headers().names()) {
44 for (CharSequence value : response.headers().getAll(name)) {
45 System.err.println("HEADER: " + name + " = " + value);
46 }
47 }
48 }
49
50 if (response.status().code() == 200 && HttpUtil.isTransferEncodingChunked(response)) {
51 readingChunks = true;
52 System.err.println("CHUNKED CONTENT {");
53 } else {
54 System.err.println("CONTENT {");
55 }
56 }
57 if (msg instanceof HttpContent) {
58 HttpContent chunk = (HttpContent) msg;
59 System.err.println(chunk.content().toString(CharsetUtil.UTF_8));
60
61 if (chunk instanceof LastHttpContent) {
62 if (readingChunks) {
63 System.err.println("} END OF CHUNKED CONTENT");
64 } else {
65 System.err.println("} END OF CONTENT");
66 }
67 readingChunks = false;
68 } else {
69 System.err.println(chunk.content().toString(CharsetUtil.UTF_8));
70 }
71 }
72 }
73
74 @Override
75 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
76 cause.printStackTrace();
77 ctx.channel().close();
78 }
79 }