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