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