1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.http.snoop;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.buffer.Unpooled;
20 import io.netty.channel.Channel;
21 import io.netty.channel.EventLoopGroup;
22 import io.netty.channel.MultiThreadIoEventLoopGroup;
23 import io.netty.channel.nio.NioIoHandler;
24 import io.netty.channel.socket.nio.NioSocketChannel;
25 import io.netty.handler.codec.http.DefaultFullHttpRequest;
26 import io.netty.handler.codec.http.HttpHeaderNames;
27 import io.netty.handler.codec.http.HttpHeaderValues;
28 import io.netty.handler.codec.http.HttpMethod;
29 import io.netty.handler.codec.http.HttpRequest;
30 import io.netty.handler.codec.http.HttpVersion;
31 import io.netty.handler.codec.http.cookie.ClientCookieEncoder;
32 import io.netty.handler.codec.http.cookie.DefaultCookie;
33 import io.netty.handler.ssl.SslContext;
34 import io.netty.handler.ssl.SslContextBuilder;
35 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
36
37 import java.net.URI;
38
39
40
41
42
43 public final class HttpSnoopClient {
44
45 static final String URL = System.getProperty("url", "http://127.0.0.1:8080/");
46
47 public static void main(String[] args) throws Exception {
48 URI uri = new URI(URL);
49 String scheme = uri.getScheme() == null? "http" : uri.getScheme();
50 String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
51 int port = uri.getPort();
52 if (port == -1) {
53 if ("http".equalsIgnoreCase(scheme)) {
54 port = 80;
55 } else if ("https".equalsIgnoreCase(scheme)) {
56 port = 443;
57 }
58 }
59
60 if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
61 System.err.println("Only HTTP(S) is supported.");
62 return;
63 }
64
65
66 final boolean ssl = "https".equalsIgnoreCase(scheme);
67 final SslContext sslCtx;
68 if (ssl) {
69 sslCtx = SslContextBuilder.forClient()
70 .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
71 } else {
72 sslCtx = null;
73 }
74
75
76 EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
77 try {
78 Bootstrap b = new Bootstrap();
79 b.group(group)
80 .channel(NioSocketChannel.class)
81 .handler(new HttpSnoopClientInitializer(sslCtx));
82
83
84 Channel ch = b.connect(host, port).sync().channel();
85
86
87 HttpRequest request = new DefaultFullHttpRequest(
88 HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath(), Unpooled.EMPTY_BUFFER);
89 request.headers().set(HttpHeaderNames.HOST, host);
90 request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
91 request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
92
93
94 request.headers().set(
95 HttpHeaderNames.COOKIE,
96 ClientCookieEncoder.STRICT.encode(
97 new DefaultCookie("my-cookie", "foo"),
98 new DefaultCookie("another-cookie", "bar")));
99
100
101 ch.writeAndFlush(request);
102
103
104 ch.closeFuture().sync();
105 } finally {
106
107 group.shutdownGracefully();
108 }
109 }
110 }