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 java.net.InetSocketAddress;
19 import java.net.URI;
20 import java.util.concurrent.Executors;
21
22 import org.jboss.netty.bootstrap.ClientBootstrap;
23 import org.jboss.netty.channel.Channel;
24 import org.jboss.netty.channel.ChannelFuture;
25 import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
26 import org.jboss.netty.handler.codec.http.CookieEncoder;
27 import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
28 import org.jboss.netty.handler.codec.http.HttpHeaders;
29 import org.jboss.netty.handler.codec.http.HttpMethod;
30 import org.jboss.netty.handler.codec.http.HttpRequest;
31 import org.jboss.netty.handler.codec.http.HttpVersion;
32
33
34
35
36
37
38
39
40
41
42
43 public class HttpClient {
44
45 public static void main(String[] args) throws Exception {
46 if (args.length != 1) {
47 System.err.println(
48 "Usage: " + HttpClient.class.getSimpleName() +
49 " <URL>");
50 return;
51 }
52
53 URI uri = new URI(args[0]);
54 String scheme = uri.getScheme() == null? "http" : uri.getScheme();
55 String host = uri.getHost() == null? "localhost" : uri.getHost();
56 int port = uri.getPort();
57 if (port == -1) {
58 if (scheme.equalsIgnoreCase("http")) {
59 port = 80;
60 } else if (scheme.equalsIgnoreCase("https")) {
61 port = 443;
62 }
63 }
64
65 if (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
66 System.err.println("Only HTTP(S) is supported.");
67 return;
68 }
69
70 boolean ssl = scheme.equalsIgnoreCase("https");
71
72
73 ClientBootstrap bootstrap = new ClientBootstrap(
74 new NioClientSocketChannelFactory(
75 Executors.newCachedThreadPool(),
76 Executors.newCachedThreadPool()));
77
78
79 bootstrap.setPipelineFactory(new HttpClientPipelineFactory(ssl));
80
81
82 ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
83
84
85 Channel channel = future.awaitUninterruptibly().getChannel();
86 if (!future.isSuccess()) {
87 future.getCause().printStackTrace();
88 bootstrap.releaseExternalResources();
89 return;
90 }
91
92
93 HttpRequest request = new DefaultHttpRequest(
94 HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
95 request.setHeader(HttpHeaders.Names.HOST, host);
96 request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
97 request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
98
99
100 CookieEncoder httpCookieEncoder = new CookieEncoder(false);
101 httpCookieEncoder.addCookie("my-cookie", "foo");
102 httpCookieEncoder.addCookie("another-cookie", "bar");
103 request.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
104
105
106 channel.write(request);
107
108
109 channel.getCloseFuture().awaitUninterruptibly();
110
111
112 bootstrap.releaseExternalResources();
113 }
114 }