use of io.netty.handler.codec.http.HttpClientCodec in project netty by netty.
the class WebSocketClientHandshaker method finishHandshake.
/**
* Validates and finishes the opening handshake initiated by {@link #handshake}}.
*
* @param channel
* Channel
* @param response
* HTTP response containing the closing handshake details
*/
public final void finishHandshake(Channel channel, FullHttpResponse response) {
verify(response);
// Verify the subprotocol that we received from the server.
// This must be one of our expected subprotocols - or null/empty if we didn't want to speak a subprotocol
String receivedProtocol = response.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
receivedProtocol = receivedProtocol != null ? receivedProtocol.trim() : null;
String expectedProtocol = expectedSubprotocol != null ? expectedSubprotocol : "";
boolean protocolValid = false;
if (expectedProtocol.isEmpty() && receivedProtocol == null) {
// No subprotocol required and none received
protocolValid = true;
// null or "" - we echo what the user requested
setActualSubprotocol(expectedSubprotocol);
} else if (!expectedProtocol.isEmpty() && receivedProtocol != null && !receivedProtocol.isEmpty()) {
// We require a subprotocol and received one -> verify it
for (String protocol : expectedProtocol.split(",")) {
if (protocol.trim().equals(receivedProtocol)) {
protocolValid = true;
setActualSubprotocol(receivedProtocol);
break;
}
}
}
if (!protocolValid) {
throw new WebSocketHandshakeException(String.format("Invalid subprotocol. Actual: %s. Expected one of: %s", receivedProtocol, expectedSubprotocol));
}
setHandshakeComplete();
final ChannelPipeline p = channel.pipeline();
// Remove decompressor from pipeline if its in use
HttpContentDecompressor decompressor = p.get(HttpContentDecompressor.class);
if (decompressor != null) {
p.remove(decompressor);
}
// Remove aggregator if present before
HttpObjectAggregator aggregator = p.get(HttpObjectAggregator.class);
if (aggregator != null) {
p.remove(aggregator);
}
ChannelHandlerContext ctx = p.context(HttpResponseDecoder.class);
if (ctx == null) {
ctx = p.context(HttpClientCodec.class);
if (ctx == null) {
throw new IllegalStateException("ChannelPipeline does not contain " + "a HttpRequestEncoder or HttpClientCodec");
}
final HttpClientCodec codec = (HttpClientCodec) ctx.handler();
// Remove the encoder part of the codec as the user may start writing frames after this method returns.
codec.removeOutboundHandler();
p.addAfter(ctx.name(), "ws-decoder", newWebsocketDecoder());
// Delay the removal of the decoder so the user can setup the pipeline if needed to handle
// WebSocketFrame messages.
// See https://github.com/netty/netty/issues/4533
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
p.remove(codec);
}
});
} else {
if (p.get(HttpRequestEncoder.class) != null) {
// Remove the encoder part of the codec as the user may start writing frames after this method returns.
p.remove(HttpRequestEncoder.class);
}
final ChannelHandlerContext context = ctx;
p.addAfter(context.name(), "ws-decoder", newWebsocketDecoder());
// Delay the removal of the decoder so the user can setup the pipeline if needed to handle
// WebSocketFrame messages.
// See https://github.com/netty/netty/issues/4533
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
p.remove(context.handler());
}
});
}
}
use of io.netty.handler.codec.http.HttpClientCodec in project netty by netty.
the class Http2ClientInitializer method configureClearText.
/**
* Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
*/
private void configureClearText(SocketChannel ch) {
HttpClientCodec sourceCodec = new HttpClientCodec();
Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler);
HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536);
ch.pipeline().addLast(sourceCodec, upgradeHandler, new UpgradeRequestHandler(), new UserEventLogger());
}
use of io.netty.handler.codec.http.HttpClientCodec in project camel by apache.
the class HttpClientInitializerFactory method initChannel.
@Override
protected void initChannel(Channel ch) throws Exception {
// create a new pipeline
ChannelPipeline pipeline = ch.pipeline();
SslHandler sslHandler = configureClientSSLOnDemand();
if (sslHandler != null) {
//TODO must close on SSL exception
//sslHandler.setCloseOnSSLException(true);
LOG.debug("Client SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler);
pipeline.addLast("ssl", sslHandler);
}
pipeline.addLast("http", new HttpClientCodec());
List<ChannelHandler> encoders = producer.getConfiguration().getEncoders();
for (int x = 0; x < encoders.size(); x++) {
ChannelHandler encoder = encoders.get(x);
if (encoder instanceof ChannelHandlerFactory) {
// use the factory to create a new instance of the channel as it may not be shareable
encoder = ((ChannelHandlerFactory) encoder).newChannelHandler();
}
pipeline.addLast("encoder-" + x, encoder);
}
List<ChannelHandler> decoders = producer.getConfiguration().getDecoders();
for (int x = 0; x < decoders.size(); x++) {
ChannelHandler decoder = decoders.get(x);
if (decoder instanceof ChannelHandlerFactory) {
// use the factory to create a new instance of the channel as it may not be shareable
decoder = ((ChannelHandlerFactory) decoder).newChannelHandler();
}
pipeline.addLast("decoder-" + x, decoder);
}
pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
if (producer.getConfiguration().getRequestTimeout() > 0) {
if (LOG.isTraceEnabled()) {
LOG.trace("Using request timeout {} millis", producer.getConfiguration().getRequestTimeout());
}
ChannelHandler timeout = new ReadTimeoutHandler(producer.getConfiguration().getRequestTimeout(), TimeUnit.MILLISECONDS);
pipeline.addLast("timeout", timeout);
}
// handler to route Camel messages
pipeline.addLast("handler", new HttpClientChannelHandler(producer));
}
use of io.netty.handler.codec.http.HttpClientCodec in project okhttp by square.
the class NettyHttpClient method prepare.
@Override
public void prepare(final Benchmark benchmark) {
this.concurrencyLevel = benchmark.concurrencyLevel;
this.targetBacklog = benchmark.targetBacklog;
ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
if (benchmark.tls) {
SslClient sslClient = SslClient.localhost();
SSLEngine engine = sslClient.sslContext.createSSLEngine();
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("inflater", new HttpContentDecompressor());
pipeline.addLast("handler", new HttpChannel(channel));
}
};
bootstrap = new Bootstrap();
bootstrap.group(new NioEventLoopGroup(concurrencyLevel)).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).channel(NioSocketChannel.class).handler(channelInitializer);
}
use of io.netty.handler.codec.http.HttpClientCodec in project riposte by Nike-Inc.
the class ComponentTestUtils method executeRequest.
public static Pair<Integer, String> executeRequest(HttpRequest request, int port, int incompleteCallTimeoutMillis) throws Exception {
Bootstrap bootstrap = new Bootstrap();
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
CompletableFuture<Pair<Integer, String>> responseFromServer = new CompletableFuture<>();
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof FullHttpResponse) {
// Store the proxyServer response for asserting on later.
FullHttpResponse responseMsg = (FullHttpResponse) msg;
responseFromServer.complete(Pair.of(responseMsg.getStatus().code(), responseMsg.content().toString(UTF_8)));
} else {
// Should never happen.
throw new RuntimeException("Received unexpected message type: " + msg.getClass());
}
}
});
}
});
// Connect to the proxyServer.
Channel ch = bootstrap.connect("localhost", port).sync().channel();
// Send the request.
ch.writeAndFlush(request);
// Wait for the response to be received
try {
responseFromServer.get(incompleteCallTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
fail("The call took much longer than expected without receiving a response. " + "Cancelling this test - it's not working properly", ex);
} finally {
ch.close();
}
// If we reach here then the call should be complete.
return responseFromServer.get();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
Aggregations