Skip to content

Commit

Permalink
Set the HOST header in Http2ClientInitializer when trying to start an…
Browse files Browse the repository at this point in the history
… upgrade request (#9177)

Motivation:

The io.netty.example.http2.helloworld.client.Http2Client example should work in the h2c (HTTP2 cleartext - non-TLS) mode, which is the default for this example unless you set a -Dssl VM param. As we do not set the HOST header some servers do reject the upgrade request.

Modifications:

Set the HOST header

Result:

Fixes #9115.
  • Loading branch information
normanmaurer committed May 27, 2019
1 parent 1e575d7 commit be7c808
Showing 1 changed file with 13 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpClientUpgradeHandler;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.DefaultHttp2Connection;
Expand All @@ -36,6 +37,8 @@
import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
import io.netty.handler.ssl.SslContext;

import java.net.InetSocketAddress;

import static io.netty.handler.logging.LogLevel.INFO;

/**
Expand Down Expand Up @@ -130,10 +133,20 @@ private void configureClearText(SocketChannel ch) {
* A handler that triggers the cleartext upgrade to HTTP/2 by sending an initial HTTP request.
*/
private final class UpgradeRequestHandler implements ChannelInboundHandler {

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
DefaultFullHttpRequest upgradeRequest =
new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");

// Set HOST header as the remote peer may require it.
InetSocketAddress remote = (InetSocketAddress) ctx.channel().remoteAddress();
String hostString = remote.getHostString();
if (hostString == null) {
hostString = remote.getAddress().getHostAddress();
}
upgradeRequest.headers().set(HttpHeaderNames.HOST, hostString + ':' + remote.getPort());

ctx.writeAndFlush(upgradeRequest);

ctx.fireChannelActive();
Expand Down

0 comments on commit be7c808

Please sign in to comment.