1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.spdy.client;
17
18 import io.netty.channel.ChannelFuture;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.channel.SimpleChannelInboundHandler;
21 import io.netty.example.http.snoop.HttpSnoopClientHandler;
22 import io.netty.handler.codec.http.HttpContent;
23 import io.netty.handler.codec.http.HttpHeaders;
24 import io.netty.handler.codec.http.HttpObject;
25 import io.netty.handler.codec.http.HttpResponse;
26 import io.netty.handler.codec.http.LastHttpContent;
27 import io.netty.util.CharsetUtil;
28
29 import java.util.concurrent.BlockingQueue;
30 import java.util.concurrent.LinkedBlockingQueue;
31
32
33
34
35
36 public class HttpResponseClientHandler extends SimpleChannelInboundHandler<HttpObject> {
37
38 private final BlockingQueue<ChannelFuture> queue = new LinkedBlockingQueue<ChannelFuture>();
39
40 @Override
41 public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
42 if (msg instanceof HttpResponse) {
43 HttpResponse response = (HttpResponse) msg;
44
45 System.out.println("STATUS: " + response.getStatus());
46 System.out.println("VERSION: " + response.getProtocolVersion());
47 System.out.println();
48
49 if (!response.headers().isEmpty()) {
50 for (String name : response.headers().names()) {
51 for (String value : response.headers().getAll(name)) {
52 System.out.println("HEADER: " + name + " = " + value);
53 }
54 }
55 System.out.println();
56 }
57
58 if (HttpHeaders.isTransferEncodingChunked(response)) {
59 System.out.println("CHUNKED CONTENT {");
60 } else {
61 System.out.println("CONTENT {");
62 }
63 }
64 if (msg instanceof HttpContent) {
65 HttpContent content = (HttpContent) msg;
66
67 System.out.print(content.content().toString(CharsetUtil.UTF_8));
68 System.out.flush();
69
70 if (content instanceof LastHttpContent) {
71 System.out.println("} END OF CONTENT");
72 queue.add(ctx.channel().newSucceededFuture());
73 }
74 }
75 }
76
77 @Override
78 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
79 queue.add(ctx.channel().newFailedFuture(cause));
80 cause.printStackTrace();
81 ctx.close();
82 }
83
84 public BlockingQueue<ChannelFuture> queue() {
85 return queue;
86 }
87 }