Example usage for io.netty.handler.codec.http HttpClientCodec HttpClientCodec

List of usage examples for io.netty.handler.codec.http HttpClientCodec HttpClientCodec

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpClientCodec HttpClientCodec.

Prototype

public HttpClientCodec(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
        boolean failOnMissingResponse, boolean validateHeaders) 

Source Link

Document

Creates a new instance with the specified decoder options.

Usage

From source file:com.vmware.xenon.common.http.netty.NettyHttpClientRequestInitializer.java

License:Open Source License

/**
 * initChannel is called by Netty when a channel is first used.
 *//*from   ww  w .ja v a  2  s.  c  om*/
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    ch.config().setAllocator(NettyChannelContext.ALLOCATOR);
    ch.config().setSendBufferSize(NettyChannelContext.BUFFER_SIZE);
    ch.config().setReceiveBufferSize(NettyChannelContext.BUFFER_SIZE);
    if (this.pool.getSSLContext() != null) {
        if (this.isHttp2Only) {
            throw new IllegalArgumentException("HTTP/2 with SSL is not supported");
        }
        SSLEngine engine = this.pool.getSSLContext().createSSLEngine();
        engine.setUseClientMode(true);
        p.addLast(SSL_HANDLER, new SslHandler(engine));
    }

    HttpClientCodec http1_codec = new HttpClientCodec(NettyChannelContext.MAX_INITIAL_LINE_LENGTH,
            NettyChannelContext.MAX_HEADER_SIZE, NettyChannelContext.MAX_CHUNK_SIZE, false, false);

    // The HttpClientCodec combines the HttpRequestEncoder and the HttpResponseDecoder, and it
    // also provides a method for upgrading the protocol, which we use to support HTTP/2.
    p.addLast(HTTP1_CODEC, http1_codec);

    if (this.isHttp2Only) {
        try {
            NettyHttpToHttp2Handler connectionHandler = makeHttp2ConnectionHandler();
            Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler);
            HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(http1_codec, upgradeCodec,
                    this.requestPayloadSizeLimit);

            p.addLast(UPGRADE_HANDLER, upgradeHandler);
            p.addLast(UPGRADE_REQUEST, new UpgradeRequestHandler());

            // This promise will be triggered when we negotiate the settings.
            // That's important because we can't send user data until the negotiation is done
            ChannelPromise settingsPromise = ch.newPromise();
            p.addLast("settings-handler", new Http2SettingsHandler(settingsPromise));
            ch.attr(NettyChannelContext.SETTINGS_PROMISE_KEY).set(settingsPromise);
            p.addLast(EVENT_LOGGER, new NettyHttp2UserEventLogger(this.debugLogging));
        } catch (Throwable ex) {
            Utils.log(NettyHttpClientRequestInitializer.class,
                    NettyHttpClientRequestInitializer.class.getSimpleName(), Level.WARNING,
                    "Channel Initializer exception: %s", ex);
            throw ex;
        }
    } else {
        // The HttpObjectAggregator is not needed for HTTP/2. For HTTP/1.1 it
        // aggregates the HttpMessage and HttpContent into the FullHttpResponse
        p.addLast(AGGREGATOR_HANDLER, new HttpObjectAggregator(this.requestPayloadSizeLimit));
    }
    p.addLast(XENON_HANDLER, new NettyHttpServerResponseHandler(this.pool));
}

From source file:io.advantageous.conekt.http.impl.HttpClientImpl.java

License:Open Source License

private void internalConnect(ContextImpl clientContext, int port, String host,
        Handler<ClientConnection> connectHandler, Handler<Throwable> connectErrorHandler,
        ConnectionLifeCycleListener listener) {
    ContextImpl context;//w w w  .  j  a va  2 s . co  m
    if (clientContext == null) {
        // Embedded
        context = vertx.getOrCreateContext();
    } else {
        context = clientContext;
    }
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(context.nettyEventLoop());
    bootstrap.channelFactory(new VertxNioSocketChannelFactory());
    sslHelper.validate(vertx);
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (options.isSsl()) {
                pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, true, host, port));
            }

            pipeline.addLast("codec", new HttpClientCodec(4096, 8192, options.getMaxChunkSize(), false, false));
            if (options.isTryUseCompression()) {
                pipeline.addLast("inflater", new HttpContentDecompressor(true));
            }
            if (options.getIdleTimeout() > 0) {
                pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
            }
            pipeline.addLast("handler", new ClientHandler(vertx, context));
        }
    });
    applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener((ChannelFuture channelFuture) -> {
        Channel ch = channelFuture.channel();
        if (channelFuture.isSuccess()) {
            if (options.isSsl()) {
                // TCP connected, so now we must do the SSL handshake

                SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
                fut.addListener(fut2 -> {
                    if (fut2.isSuccess()) {
                        connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
                    } else {
                        SSLHandshakeException sslException = new SSLHandshakeException(
                                "Failed to create SSL connection");
                        Optional.ofNullable(fut2.cause()).ifPresent(sslException::initCause);
                        connectionFailed(context, ch, connectErrorHandler, sslException, listener);
                    }
                });
            } else {
                connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
            }
        } else {
            connectionFailed(context, ch, connectErrorHandler, channelFuture.cause(), listener);
        }
    });
}

From source file:io.jsync.http.impl.DefaultHttpClient.java

License:Open Source License

void internalConnect(final Handler<ClientConnection> connectHandler,
        final Handler<Throwable> connectErrorHandler) {
    if (bootstrap == null) {
        // Share the event loop thread to also serve the HttpClient's network traffic.
        AsyncEventLoopGroup pool = new AsyncEventLoopGroup();
        pool.addWorker(actualCtx.getEventLoop());
        bootstrap = new Bootstrap();
        bootstrap.group(pool);//  w w w .  j av  a 2  s.  c  o m
        bootstrap.channel(NioSocketChannel.class);
        tcpHelper.checkSSL(async);

        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (tcpHelper.isSSL()) {
                    pipeline.addLast("ssl", tcpHelper.createSslHandler(async, true, host, port));
                }
                pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false));
                if (tryUseCompression) {
                    pipeline.addLast("inflater", new HttpContentDecompressor(true));
                }
                pipeline.addLast("handler", new ClientHandler());
            }
        });
    }
    tcpHelper.applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            final Channel ch = channelFuture.channel();
            if (channelFuture.isSuccess()) {
                if (tcpHelper.isSSL()) {
                    // TCP connected, so now we must do the SSL handshake

                    SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                    Future<Channel> fut = sslHandler.handshakeFuture();
                    fut.addListener(new GenericFutureListener<Future<Channel>>() {
                        @Override
                        public void operationComplete(Future<Channel> future) throws Exception {
                            if (future.isSuccess()) {
                                connected(ch, connectHandler);
                            } else {
                                connectionFailed(ch, connectErrorHandler,
                                        new SSLHandshakeException("Failed to create SSL connection"));
                            }
                        }
                    });
                } else {
                    connected(ch, connectHandler);
                }
            } else {
                connectionFailed(ch, connectErrorHandler, channelFuture.cause());
            }
        }
    });
}

From source file:io.reactivex.netty.protocol.http.client.HttpClientPipelineConfigurator.java

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    pipeline.addLast(HTTP_CODEC_HANDLER_NAME, new HttpClientCodec(maxInitialLineLength, maxHeaderSize,
            maxChunkSize, failOnMissingResponse, validateHeaders));
}

From source file:io.vertx.core.http.impl.HttpClientImpl.java

License:Open Source License

private void internalConnect(ContextImpl context, int port, String host,
        Handler<ClientConnection> connectHandler, Handler<Throwable> connectErrorHandler,
        ConnectionLifeCycleListener listener) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(context.eventLoop());
    bootstrap.channelFactory(new VertxNioSocketChannelFactory());
    sslHelper.validate(vertx);//from w w  w  .  j av a 2s  . com
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (options.isSsl()) {
                pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, true, host, port));
            }

            pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false));
            if (options.isTryUseCompression()) {
                pipeline.addLast("inflater", new HttpContentDecompressor(true));
            }
            if (options.getIdleTimeout() > 0) {
                pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
            }
            pipeline.addLast("handler", new ClientHandler(vertx, context));
        }
    });
    applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener((ChannelFuture channelFuture) -> {
        Channel ch = channelFuture.channel();
        if (channelFuture.isSuccess()) {
            if (options.isSsl()) {
                // TCP connected, so now we must do the SSL handshake

                SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
                fut.addListener(fut2 -> {
                    if (fut2.isSuccess()) {
                        connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
                    } else {
                        connectionFailed(context, ch, connectErrorHandler,
                                new SSLHandshakeException("Failed to create SSL connection"), listener);
                    }
                });
            } else {
                connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
            }
        } else {
            connectionFailed(context, ch, connectErrorHandler, channelFuture.cause(), listener);
        }
    });
}

From source file:org.asynchttpclient.netty.channel.ChannelManager.java

License:Open Source License

private HttpClientCodec newHttpClientCodec() {
    return new HttpClientCodec(//
            config.getHttpClientCodecMaxInitialLineLength(), //
            config.getHttpClientCodecMaxHeaderSize(), //
            config.getHttpClientCodecMaxChunkSize(), //
            false, //
            config.isValidateResponseHeaders());
}

From source file:org.vertx.java.core.http.impl.DefaultHttpClient.java

License:Open Source License

void internalConnect(final Handler<ClientConnection> connectHandler,
        final Handler<Throwable> connectErrorHandler) {
    if (bootstrap == null) {
        // Share the event loop thread to also serve the HttpClient's network traffic.
        VertxEventLoopGroup pool = new VertxEventLoopGroup();
        pool.addWorker(actualCtx.getEventLoop());
        bootstrap = new Bootstrap();
        bootstrap.group(pool);/*w  w  w.java  2  s.  co m*/
        bootstrap.channel(NioSocketChannel.class);
        tcpHelper.checkSSL(vertx);

        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (tcpHelper.isSSL()) {
                    SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine(host, port);
                    if (tcpHelper.isVerifyHost()) {
                        SSLParameters sslParameters = engine.getSSLParameters();
                        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                        engine.setSSLParameters(sslParameters);
                    }
                    engine.setUseClientMode(true); //We are on the client side of the connection
                    pipeline.addLast("ssl", new SslHandler(engine));
                }

                pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false));
                if (tryUseCompression) {
                    pipeline.addLast("inflater", new HttpContentDecompressor(true));
                }
                pipeline.addLast("handler", new ClientHandler());
            }
        });
    }
    tcpHelper.applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            final Channel ch = channelFuture.channel();
            if (channelFuture.isSuccess()) {
                if (tcpHelper.isSSL()) {
                    // TCP connected, so now we must do the SSL handshake

                    SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                    Future<Channel> fut = sslHandler.handshakeFuture();
                    fut.addListener(new GenericFutureListener<Future<Channel>>() {
                        @Override
                        public void operationComplete(Future<Channel> future) throws Exception {
                            if (future.isSuccess()) {
                                connected(ch, connectHandler);
                            } else {
                                connectionFailed(ch, connectErrorHandler,
                                        new SSLHandshakeException("Failed to create SSL connection"));
                            }
                        }
                    });
                } else {
                    connected(ch, connectHandler);
                }
            } else {
                connectionFailed(ch, connectErrorHandler, channelFuture.cause());
            }
        }
    });
}