View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License, version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * 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 distributed under the License
11   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  package io.netty.example.http2.client;
16  
17  import io.netty.bootstrap.Bootstrap;
18  import io.netty.buffer.Unpooled;
19  import io.netty.channel.Channel;
20  import io.netty.channel.ChannelOption;
21  import io.netty.channel.EventLoopGroup;
22  import io.netty.channel.nio.NioEventLoopGroup;
23  import io.netty.channel.socket.nio.NioSocketChannel;
24  import io.netty.handler.codec.http.DefaultFullHttpRequest;
25  import io.netty.handler.codec.http.FullHttpRequest;
26  import io.netty.handler.codec.http.HttpHeaderNames;
27  import io.netty.handler.codec.http.HttpHeaderValues;
28  import io.netty.handler.codec.http2.Http2OrHttpChooser.SelectedProtocol;
29  import io.netty.handler.codec.http2.Http2SecurityUtil;
30  import io.netty.handler.ssl.ApplicationProtocolConfig;
31  import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
32  import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
33  import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
34  import io.netty.handler.ssl.SslContext;
35  import io.netty.handler.ssl.SslProvider;
36  import io.netty.handler.ssl.SupportedCipherSuiteFilter;
37  import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
38  import io.netty.util.CharsetUtil;
39  
40  import java.net.URI;
41  import java.util.concurrent.TimeUnit;
42  
43  import static io.netty.handler.codec.http.HttpMethod.*;
44  import static io.netty.handler.codec.http.HttpVersion.*;
45  
46  /**
47   * An HTTP2 client that allows you to send HTTP2 frames to a server. Inbound and outbound frames are
48   * logged. When run from the command-line, sends a single HEADERS frame to the server and gets back
49   * a "Hello World" response.
50   */
51  public final class Http2Client {
52  
53      static final boolean SSL = System.getProperty("ssl") != null;
54      static final String HOST = System.getProperty("host", "127.0.0.1");
55      static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080"));
56      static final String URL = System.getProperty("url", "/whatever");
57      static final String URL2 = System.getProperty("url2");
58      static final String URL2DATA = System.getProperty("url2data", "test data!");
59  
60      public static void main(String[] args) throws Exception {
61          // Configure SSL.
62          final SslContext sslCtx;
63          if (SSL) {
64              sslCtx = SslContext.newClientContext(SslProvider.JDK,
65                      null, InsecureTrustManagerFactory.INSTANCE,
66                      Http2SecurityUtil.CIPHERS,
67                      /* NOTE: the following filter may not include all ciphers required by the HTTP/2 specification
68                       * Please refer to the HTTP/2 specification for cipher requirements. */
69                      SupportedCipherSuiteFilter.INSTANCE,
70                      new ApplicationProtocolConfig(
71                              Protocol.ALPN,
72                              SelectorFailureBehavior.FATAL_ALERT,
73                              SelectedListenerFailureBehavior.FATAL_ALERT,
74                              SelectedProtocol.HTTP_2.protocolName(),
75                              SelectedProtocol.HTTP_1_1.protocolName()),
76                      0, 0);
77          } else {
78              sslCtx = null;
79          }
80  
81          EventLoopGroup workerGroup = new NioEventLoopGroup();
82          Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);
83  
84          try {
85              // Configure the client.
86              Bootstrap b = new Bootstrap();
87              b.group(workerGroup);
88              b.channel(NioSocketChannel.class);
89              b.option(ChannelOption.SO_KEEPALIVE, true);
90              b.remoteAddress(HOST, PORT);
91              b.handler(initializer);
92  
93              // Start the client.
94              Channel channel = b.connect().syncUninterruptibly().channel();
95              System.out.println("Connected to [" + HOST + ':' + PORT + ']');
96  
97              // Wait for the HTTP/2 upgrade to occur.
98              Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
99              http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);
100 
101             HttpResponseHandler responseHandler = initializer.responseHandler();
102             int streamId = 3;
103             URI hostName = URI.create((SSL ? "https" : "http") + "://" + HOST + ':' + PORT);
104             System.err.println("Sending request(s)...");
105             if (URL != null) {
106                 // Create a simple GET request.
107                 FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
108                 request.headers().addObject(HttpHeaderNames.HOST, hostName);
109                 request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
110                 request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
111                 channel.writeAndFlush(request);
112                 responseHandler.put(streamId, channel.newPromise());
113                 streamId += 2;
114             }
115             if (URL2 != null) {
116                 // Create a simple POST request with a body.
117                 FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
118                                 Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
119                 request.headers().addObject(HttpHeaderNames.HOST, hostName);
120                 request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
121                 request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
122                 channel.writeAndFlush(request);
123                 responseHandler.put(streamId, channel.newPromise());
124                 streamId += 2;
125             }
126             responseHandler.awaitResponses(5, TimeUnit.SECONDS);
127             System.out.println("Finished HTTP/2 request(s)");
128 
129             // Wait until the connection is closed.
130             channel.close().syncUninterruptibly();
131         } finally {
132             workerGroup.shutdownGracefully();
133         }
134     }
135 }