View Javadoc

1   /*
2    * Copyright 2009 Red Hat, Inc.
3    *
4    * Red Hat licenses this file to you under the Apache License, version 2.0
5    * (the "License"); you may not use this file except in compliance with the
6    * License.  You may obtain a copy of the License at:
7    *
8    *    http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * A simple HTTP client that prints out the content of the HTTP response to
35   * {@link System#out} to test {@link HttpServer}.
36   *
37   * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
38   * @author Andy Taylor (andy.taylor@jboss.org)
39   * @author <a href="http://gleamynode.net/">Trustin Lee</a>
40   *
41   * @version $Rev: 2226 $, $Date: 2010-03-31 11:26:51 +0900 (Wed, 31 Mar 2010) $
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          // Configure the client.
73          ClientBootstrap bootstrap = new ClientBootstrap(
74                  new NioClientSocketChannelFactory(
75                          Executors.newCachedThreadPool(),
76                          Executors.newCachedThreadPool()));
77  
78          // Set up the event pipeline factory.
79          bootstrap.setPipelineFactory(new HttpClientPipelineFactory(ssl));
80  
81          // Start the connection attempt.
82          ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
83  
84          // Wait until the connection attempt succeeds or fails.
85          Channel channel = future.awaitUninterruptibly().getChannel();
86          if (!future.isSuccess()) {
87              future.getCause().printStackTrace();
88              bootstrap.releaseExternalResources();
89              return;
90          }
91  
92          // Prepare the HTTP request.
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          // Set some example cookies.
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         // Send the HTTP request.
106         channel.write(request);
107 
108         // Wait for the server to close the connection.
109         channel.getCloseFuture().awaitUninterruptibly();
110 
111         // Shut down executor threads to exit.
112         bootstrap.releaseExternalResources();
113     }
114 }