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