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    * https://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.helloworld.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.MultiThreadIoEventLoopGroup;
23  import io.netty.channel.nio.NioIoHandler;
24  import io.netty.channel.socket.nio.NioSocketChannel;
25  import io.netty.handler.codec.http.DefaultFullHttpRequest;
26  import io.netty.handler.codec.http.FullHttpRequest;
27  import io.netty.handler.codec.http.HttpHeaderNames;
28  import io.netty.handler.codec.http.HttpHeaderValues;
29  import io.netty.handler.codec.http.HttpScheme;
30  import io.netty.handler.codec.http2.Http2SecurityUtil;
31  import io.netty.handler.codec.http2.HttpConversionUtil;
32  import io.netty.handler.ssl.ApplicationProtocolConfig;
33  import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
34  import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
35  import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
36  import io.netty.handler.ssl.ApplicationProtocolNames;
37  import io.netty.handler.ssl.OpenSsl;
38  import io.netty.handler.ssl.SslContext;
39  import io.netty.handler.ssl.SslContextBuilder;
40  import io.netty.handler.ssl.SslProvider;
41  import io.netty.handler.ssl.SupportedCipherSuiteFilter;
42  import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
43  import io.netty.util.AsciiString;
44  import io.netty.util.CharsetUtil;
45  
46  import java.util.concurrent.TimeUnit;
47  
48  import static io.netty.buffer.Unpooled.wrappedBuffer;
49  import static io.netty.handler.codec.http.HttpMethod.GET;
50  import static io.netty.handler.codec.http.HttpMethod.POST;
51  import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
52  
53  /**
54   * An HTTP2 client that allows you to send HTTP2 frames to a server using HTTP1-style approaches
55   * (via {@link io.netty.handler.codec.http2.InboundHttp2ToHttpAdapter}). Inbound and outbound
56   * frames are logged.
57   * When run from the command-line, sends a single HEADERS frame to the server and gets back
58   * a "Hello World" response.
59   * See the ./http2/helloworld/frame/client/ example for a HTTP2 client example which does not use
60   * HTTP1-style objects and patterns.
61   */
62  public final class Http2Client {
63  
64      static final boolean SSL = System.getProperty("ssl") != null;
65      static final String HOST = System.getProperty("host", "127.0.0.1");
66      static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080"));
67      static final String URL = System.getProperty("url", "/whatever");
68      static final String URL2 = System.getProperty("url2");
69      static final String URL2DATA = System.getProperty("url2data", "test data!");
70  
71      public static void main(String[] args) throws Exception {
72          // Configure SSL.
73          final SslContext sslCtx;
74          if (SSL) {
75              SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
76              sslCtx = SslContextBuilder.forClient()
77                  .sslProvider(provider)
78                  /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
79                   * Please refer to the HTTP/2 specification for cipher requirements. */
80                  .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
81                  .trustManager(InsecureTrustManagerFactory.INSTANCE)
82                  .applicationProtocolConfig(new ApplicationProtocolConfig(
83                      Protocol.ALPN,
84                      // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
85                      SelectorFailureBehavior.NO_ADVERTISE,
86                      // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
87                      SelectedListenerFailureBehavior.ACCEPT,
88                      ApplicationProtocolNames.HTTP_2,
89                      ApplicationProtocolNames.HTTP_1_1))
90                  .build();
91          } else {
92              sslCtx = null;
93          }
94  
95          EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
96          Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);
97  
98          try {
99              // Configure the client.
100             Bootstrap b = new Bootstrap();
101             b.group(group);
102             b.channel(NioSocketChannel.class);
103             b.option(ChannelOption.SO_KEEPALIVE, true);
104             b.remoteAddress(HOST, PORT);
105             b.handler(initializer);
106 
107             // Start the client.
108             Channel channel = b.connect().syncUninterruptibly().channel();
109             System.out.println("Connected to [" + HOST + ':' + PORT + ']');
110 
111             // Wait for the HTTP/2 upgrade to occur.
112             Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
113             http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);
114 
115             HttpResponseHandler responseHandler = initializer.responseHandler();
116             int streamId = 3;
117             HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
118             AsciiString hostName = new AsciiString(HOST + ':' + PORT);
119             System.err.println("Sending request(s)...");
120             if (URL != null) {
121                 // Create a simple GET request.
122                 FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL, Unpooled.EMPTY_BUFFER);
123                 request.headers().add(HttpHeaderNames.HOST, hostName);
124                 request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
125                 request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
126                 request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
127                 responseHandler.put(streamId, channel.write(request), channel.newPromise());
128                 streamId += 2;
129             }
130             if (URL2 != null) {
131                 // Create a simple POST request with a body.
132                 FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
133                         wrappedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
134                 request.headers().add(HttpHeaderNames.HOST, hostName);
135                 request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
136                 request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
137                 request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
138                 responseHandler.put(streamId, channel.write(request), channel.newPromise());
139             }
140             channel.flush();
141             responseHandler.awaitResponses(5, TimeUnit.SECONDS);
142             System.out.println("Finished HTTP/2 request(s)");
143 
144             // Wait until the connection is closed.
145             channel.close().syncUninterruptibly();
146         } finally {
147             group.shutdownGracefully();
148         }
149     }
150 }