Java 类io.netty.handler.codec.http.HttpRequestEncoder 实例源码

项目:mpush    文件:NettyHttpClient.java   
@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}
项目:GameServerFramework    文件:NHttpRequest.java   
@Override
public void configNewChannel(NioSocketChannel channel) {
    super.configNewChannel(channel);
    ChannelPipeline pipeline = channel.pipeline();
    // 添加 SSL 数据支持
    if (requestConfig.https()) {
        SslContext sslContent = NettyCenter.singleInstance().getSimpleClientSslContext();
        SSLEngine engine = sslContent.newEngine(channel.alloc());
        pipeline.addLast("ssl", new SslHandler(engine));
    }
    // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
    pipeline.addLast("decoder", new HttpResponseDecoder());
    // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
    pipeline.addLast("encoder", new HttpRequestEncoder());
    // 接收的请求累计器
    pipeline.addLast("aggegator", new HttpObjectAggregator(0x30000));
    // mime 类型写出
    pipeline.addLast("streamew", new ChunkedWriteHandler());
    // 添加解压器
    pipeline.addLast("decompressor", new HttpContentDecompressor());
    // add new handler
    pipeline.addLast("handler", new NettyHttpRequestChannelHandler());
}
项目:carbon-transports    文件:RedirectChannelInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (sslEngine != null) {
        if (log.isDebugEnabled()) {
            log.debug("adding ssl handler");
        }
        ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
    }
    ch.pipeline().addLast("compressor", new HttpContentCompressor());
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    if (httpTraceLogEnabled) {
        ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
                new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
    }
    RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount
            , chunkDisabled, originalChannelContext, isIdleHandlerOfTargetChannelRemoved);
    ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
}
项目:carbon-transports    文件:HTTPClientRedirectTestCase.java   
/**
 * Check whether, redirect request is written to the backend when a redirect response is received.
 *
 * @throws URISyntaxException
 * @throws IOException
 */
@Test
public void unitTestForRedirectHandler() throws URISyntaxException, IOException {
    EmbeddedChannel embeddedChannel = new EmbeddedChannel();
    embeddedChannel.pipeline().addLast(new HttpResponseDecoder());
    embeddedChannel.pipeline().addLast(new HttpRequestEncoder());
    embeddedChannel.pipeline().addLast(new RedirectHandler(null, false, 5, false));
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT,
            Unpooled.EMPTY_BUFFER);
    response.headers().set(HttpHeaders.Names.LOCATION, FINAL_DESTINATION);
    embeddedChannel.attr(Constants.ORIGINAL_REQUEST)
            .set(createHttpRequest(Constants.HTTP_GET_METHOD, FINAL_DESTINATION));
    embeddedChannel.writeInbound(response);
    embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    assertNotNull(embeddedChannel.readOutbound());
}
项目:carbon-transports    文件:HTTPClientRedirectTestCase.java   
/**
 * When the maximum redirect count reached, channel should not do any more redirects.
 *
 * @throws URISyntaxException
 * @throws IOException
 */
@Test
public void unitTestForRedirectLoop() throws URISyntaxException, IOException {
    EmbeddedChannel embeddedChannel = new EmbeddedChannel();
    embeddedChannel.pipeline().addLast(new HttpResponseDecoder());
    embeddedChannel.pipeline().addLast(new HttpRequestEncoder());
    embeddedChannel.pipeline()
            .addLast(Constants.IDLE_STATE_HANDLER, new IdleStateHandler(50000, 50000, 0, TimeUnit.MILLISECONDS));
    embeddedChannel.pipeline().addLast(new RedirectHandler(null, false, 5, false, null, false));
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT,
            Unpooled.EMPTY_BUFFER);
    response.headers().set(HttpHeaders.Names.LOCATION, FINAL_DESTINATION);
    embeddedChannel.attr(Constants.ORIGINAL_REQUEST)
            .set(createHttpRequest(Constants.HTTP_GET_METHOD, FINAL_DESTINATION));
    embeddedChannel.attr(Constants.RESPONSE_FUTURE_OF_ORIGINAL_CHANNEL).set(new HttpResponseFutureImpl());
    TargetChannel targetChannel = new TargetChannel(null, null);
    targetChannel.setChannel(embeddedChannel);
    embeddedChannel.attr(Constants.TARGET_CHANNEL_REFERENCE).set(targetChannel);
    embeddedChannel.attr(Constants.REDIRECT_COUNT).set(5);
    embeddedChannel.writeInbound(response);
    embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    assertNull(embeddedChannel.readOutbound());
}
项目:urmia    文件:HttpProxyBackendInitializer.java   
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();


    if(directWriteBack) {
        p.addLast("encoder", new HttpRequestEncoder());
        p.addLast(new DirectWriteBackHttpProxyBackendHandler(inboundCtx.channel()));
    } else {
        p.addLast("encoder", new HttpRequestEncoder());

        p.addLast("decoder", new HttpResponseDecoder());
        //p.addLast("aggregator", new HttpObjectAggregator(2048));
        p.addLast(new HttpProxyBackendHandler(inboundCtx, index));
    }

}
项目:util4j    文件:HttpClientInitHandler.java   
@Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        if(sslCtx!=null)
        {
            p.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
        }
        p.addLast(new HttpResponseDecoder());
        //限制contentLength
        p.addLast(new HttpObjectAggregator(65536));
        p.addLast(new HttpRequestEncoder());
        //大文件传输处理
//      p.addLast(new ChunkedWriteHandler());
        p.addLast(new DefaultListenerHandler<HttpResponse>(listener));
    }
项目:hadoop    文件:SimpleHttpProxyHandler.java   
@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.getUri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.getMethod(), req.getUri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, Values.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, Values.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}
项目:aliyun-oss-hadoop-fs    文件:SimpleHttpProxyHandler.java   
@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.uri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.method(), req.uri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}
项目:study-netty    文件:HttpClient.java   
public void connect(String host, int port) throws Exception {
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
                ch.pipeline().addLast(new HttpResponseDecoder());
                // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
                ch.pipeline().addLast(new HttpRequestEncoder());
                ch.pipeline().addLast(new HttpClientInboundHandler());
            }
        });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();

        URI uri = new URI("http://127.0.0.1:8844");
        String msg = "Are you ok?";
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));

        // 构建http请求
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
        // 发送http请求
        f.channel().write(request);
        f.channel().flush();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }

}
项目:big-c    文件:SimpleHttpProxyHandler.java   
@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.getUri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.getMethod(), req.getUri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, Values.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, Values.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}
项目:riposte    文件:StreamingAsyncHttpClient.java   
protected static int determineHttpClientCodecOutboundState(HttpClientCodec currentCodec) {
    try {
        HttpRequestEncoder encoder = (HttpRequestEncoder) httpClientCodecOutboundHandlerField.get(currentCodec);
        return httpObjectEncoderStateField.getInt(encoder);
    }
    catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
项目:netty-tutorials    文件:HttpXmlClient.java   
public void connect(int port) throws Exception {
    // 配置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch)
                            throws Exception {
                        ch.pipeline().addLast("http-decoder",
                                new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator",
                                new HttpObjectAggregator(65536));
                        // XML解码器
                        ch.pipeline().addLast(
                                "xml-decoder",
                                new HttpXmlResponseDecoder(Order.class,
                                        true));
                        ch.pipeline().addLast("http-encoder",
                                new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder",
                                new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler",
                                new HttpXmlClientHandler());
                    }
                });

        // 发起异步连接操作
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 当代客户端链路关闭
        f.channel().closeFuture().sync();
    } finally {
        // 优雅退出,释放NIO线程组
        group.shutdownGracefully();
    }
}
项目:zbus    文件:ProxyClient.java   
public ProxyClient(String address, final EventLoop loop) {  
    super(address, loop);     

    codec(new CodecInitializer() {
        @Override
        public void initPipeline(List<ChannelHandler> p) {
            p.add(new HttpRequestEncoder()); 
            p.add(new HttpResponseDecoder());  
            p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
            p.add(new MessageCodec());
        }
    });  

    onDisconnected(new DisconnectedHandler() { 
        @Override
        public void onDisconnected() throws IOException {
            log.info("Disconnected from(%s) ID=%s", serverAddress(), clientId);
            ProxyClient.this.close();
        }
    }); 

    onError(new ErrorHandler() { 
        @Override
        public void onError(Throwable e, Session session) throws IOException {
            ProxyClient.this.close();
        }
    });
}
项目:zbus    文件:MessageClient.java   
protected void initSupport(ServerAddress address, final EventLoop loop){
    if(address.getServer() != null){
        support = new InProcClient<Message, Message>(address.getServer().getIoAdaptor());
        return;
    }

    TcpClient<Message, Message> tcp = new TcpClient<Message, Message>(address, loop);
    support = tcp;

    tcp.codec(new CodecInitializer() {
        @Override
        public void initPipeline(List<ChannelHandler> p) {
            p.add(new HttpRequestEncoder()); 
            p.add(new HttpResponseDecoder());  
            p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
            p.add(new MessageCodec());
        }
    }); 

    tcp.startHeartbeat(heartbeatInterval, new HeartbeatMessageBuilder<Message>() { 
        @Override
        public Message build() { 
            Message hbt = new Message();
            hbt.setCommand(Message.HEARTBEAT);
            return hbt;
        } 
    });  
}
项目:little_mitm    文件:ProxyToServerConnection.java   
/**
 * Initialize our {@link ChannelPipeline}.
 * 
 * @param pipeline
 * @param httpRequest
 */
private void initChannelPipeline(ChannelPipeline pipeline,
        HttpRequest httpRequest) {

    if (trafficHandler != null) {
        pipeline.addLast("global-traffic-shaping", trafficHandler);
    }

    pipeline.addLast("bytesReadMonitor", bytesReadMonitor);
    pipeline.addLast("decoder", new HeadAwareHttpResponseDecoder(
            8192,
            8192 * 2,
            8192 * 2));
    pipeline.addLast("responseReadMonitor", responseReadMonitor);

    // Enable aggregation for filtering if necessary
    int numberOfBytesToBuffer = proxyServer.getFiltersSource()
            .getMaximumResponseBufferSizeInBytes();
    if (numberOfBytesToBuffer > 0) {
        aggregateContentForFiltering(pipeline, numberOfBytesToBuffer);
    }

    pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor);
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("requestWrittenMonitor", requestWrittenMonitor);

    // Set idle timeout
    pipeline.addLast(
            "idle",
            new IdleStateHandler(0, 0, proxyServer
                    .getIdleConnectionTimeout()));

    pipeline.addLast("handler", this);
}
项目:flashback    文件:ChannelMediator.java   
private void initChannelPipeline(ChannelPipeline pipeline, ServerChannelHandler serverChannelHandler,
    int idleTimeoutMsec) {
  pipeline.addLast("decoder", new HttpResponseDecoder());
  pipeline.addLast("encoder", new HttpRequestEncoder());
  pipeline.addLast("idle", new IdleStateHandler(0, 0, idleTimeoutMsec / 1000));
  pipeline.addLast("handler", serverChannelHandler);
}
项目:LittleProxy    文件:ProxyToServerConnection.java   
/**
 * Initialize our {@link ChannelPipeline}.
 * 
 * @param pipeline
 * @param httpRequest
 */
private void initChannelPipeline(ChannelPipeline pipeline,
        HttpRequest httpRequest) {

    if (trafficHandler != null) {
        pipeline.addLast("global-traffic-shaping", trafficHandler);
    }

    pipeline.addLast("bytesReadMonitor", bytesReadMonitor);
    pipeline.addLast("decoder", new HeadAwareHttpResponseDecoder(
            8192,
            8192 * 2,
            8192 * 2));
    pipeline.addLast("responseReadMonitor", responseReadMonitor);

    if (!ProxyUtils.isCONNECT(httpRequest)) {
        // Enable aggregation for filtering if necessary
        int numberOfBytesToBuffer = proxyServer.getFiltersSource()
                .getMaximumResponseBufferSizeInBytes();
        if (numberOfBytesToBuffer > 0) {
            aggregateContentForFiltering(pipeline, numberOfBytesToBuffer);
        }
    }

    pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor);
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("requestWrittenMonitor", requestWrittenMonitor);

    // Set idle timeout
    pipeline.addLast(
            "idle",
            new IdleStateHandler(0, 0, proxyServer
                    .getIdleConnectionTimeout()));

    pipeline.addLast("handler", this);
}
项目:netty-book    文件:HttpXmlClient.java   
public void connect(int port) throws Exception {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch)
            throws Exception {
            ch.pipeline().addLast("http-decoder",
                new HttpResponseDecoder());
            ch.pipeline().addLast("http-aggregator",
                new HttpObjectAggregator(65536));
            // XML解码器
            ch.pipeline().addLast(
                "xml-decoder",
                new HttpXmlResponseDecoder(Order.class,
                    true));
            ch.pipeline().addLast("http-encoder",
                new HttpRequestEncoder());
            ch.pipeline().addLast("xml-encoder",
                new HttpXmlRequestEncoder());
            ch.pipeline().addLast("xmlClientHandler",
                new HttpXmlClientHandle());
        }
        });

    // 发起异步连接操作
    ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

    // 当代客户端链路关闭
    f.channel().closeFuture().sync();
} finally {
    // 优雅退出,释放NIO线程组
    group.shutdownGracefully();
}
   }
项目:netty4.0.27Learn    文件:WebSocketClientHandshaker.java   
/**
 * Begins the opening handshake
 *
 * @param channel
 *            Channel
 * @param promise
 *            the {@link ChannelPromise} to be notified when the opening handshake is sent
 */
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
    FullHttpRequest request =  newHandshakeRequest();

    HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
    if (decoder == null) {
        HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
        if (codec == null) {
           promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                   "a HttpResponseDecoder or HttpClientCodec"));
           return promise;
        }
    }

    channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = future.channel().pipeline();
                ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                if (ctx == null) {
                    ctx = p.context(HttpClientCodec.class);
                }
                if (ctx == null) {
                    promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                            "a HttpRequestEncoder or HttpClientCodec"));
                    return;
                }
                p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());

                promise.setSuccess();
            } else {
                promise.setFailure(future.cause());
            }
        }
    });
    return promise;
}
项目:hope-tactical-equipment    文件:HttpXmlClient.java   
public void connect(int port) throws Exception {
    // 配置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch)
                            throws Exception {
                        ch.pipeline().addLast("http-decoder",
                                new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator",
                                new HttpObjectAggregator(65536));
                        // XML解码器
                        ch.pipeline().addLast(
                                "xml-decoder",
                                new HttpXmlResponseDecoder(Order.class,
                                        true));
                        ch.pipeline().addLast("http-encoder",
                                new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder",
                                new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler",
                                new HttpXmlClientHandle());
                    }
                });

        // 发起异步连接操作
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 当代客户端链路关闭
        f.channel().closeFuture().sync();
    } finally {
        // 优雅退出,释放NIO线程组
        group.shutdownGracefully();
    }
}
项目:carbon-transports    文件:HTTPClientInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (proxyServerConfiguration != null) {
        if (proxyServerConfiguration.getProxyUsername() != null
                && proxyServerConfiguration.getProxyPassword() != null) {
            ch.pipeline().addLast("proxyServer",
                    new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress(),
                            proxyServerConfiguration.getProxyUsername(),
                            proxyServerConfiguration.getProxyPassword()));
        } else {
            ch.pipeline()
                    .addLast("proxyServer", new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress()));
        }
    }
    if (sslEngine != null) {
        log.debug("adding ssl handler");
        ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
    }
    ch.pipeline().addLast("compressor", new CustomHttpContentCompressor(chunkDisabled));
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    ch.pipeline().addLast("chunkWriter", new ChunkedWriteHandler());
    if (httpTraceLogEnabled) {
        ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
                              new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
    }
    if (followRedirect) {
        if (log.isDebugEnabled()) {
            log.debug("Follow Redirect is enabled, so adding the redirect handler to the pipeline.");
        }
        RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount
                , chunkDisabled);
        ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
    }
    handler = new TargetHandler();
    ch.pipeline().addLast(Constants.TARGET_HANDLER, handler);
}
项目:jetstream    文件:HttpClient.java   
private void createChannelPipeline() {

        if (isPipelineCreated())
            return;

        m_workerGroup = new NioEventLoopGroup(getConfig().getNumWorkers(), new NameableThreadFactory("Jetstream-HttpClientWorker"));
        m_bootstrap = new Bootstrap();
        m_bootstrap.group(m_workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,  getConfig()
                .getConnectionTimeoutInSecs())
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("timeout", new IdleStateHandler(0, getConfig().getIdleTimeoutInSecs(), 0));
                        ch.pipeline().addLast("decoder", new HttpResponseDecoder());
                        ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                        ch.pipeline().addLast("encoder", new HttpRequestEncoder());
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(m_config.getMaxContentLength()));
                        ch.pipeline().addLast(m_httpRequestHandler);
                    }
                });

        if (getConfig().getRvcBufSz() > 0) {
            m_bootstrap.option(ChannelOption.SO_RCVBUF, (int) getConfig().getRvcBufSz());
        }

        if ( getConfig().getSendBufSz() > 0) {
            m_bootstrap.option(ChannelOption.SO_SNDBUF, (int) getConfig().getSendBufSz());
        }
        createdPipeline();

    }
项目:javase-study    文件:HttpDecoderEncoderInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    if (client) {
        pipeline.addLast("decoder", new HttpResponseDecoder());
        pipeline.addLast("encoder", new HttpRequestEncoder());
    } else {
        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("encoder", new HttpResponseEncoder());
    }
}
项目:netty4study    文件:WebSocketClientHandshaker.java   
/**
 * Begins the opening handshake
 *
 * @param channel
 *            Channel
 * @param promise
 *            the {@link ChannelPromise} to be notified when the opening handshake is sent
 */
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
    FullHttpRequest request =  newHandshakeRequest();

    HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
    if (decoder == null) {
        HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
        if (codec == null) {
           promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                   "a HttpResponseDecoder or HttpClientCodec"));
           return promise;
        }
    }

    channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = future.channel().pipeline();
                ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                if (ctx == null) {
                    ctx = p.context(HttpClientCodec.class);
                }
                if (ctx == null) {
                    promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                            "a HttpRequestEncoder or HttpClientCodec"));
                    return;
                }
                p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());

                promise.setSuccess();
            } else {
                promise.setFailure(future.cause());
            }
        }
    });
    return promise;
}
项目:netty4study    文件:WebSocketClientHandshaker.java   
/**
 * 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);
    setActualSubprotocol(response.headers().get(HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL));
    setHandshakeComplete();

    ChannelPipeline p = channel.pipeline();
    // Remove decompressor from pipeline if its in use
    HttpContentDecompressor decompressor = p.get(HttpContentDecompressor.class);
    if (decompressor != null) {
        p.remove(decompressor);
    }

    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");
        }
        p.replace(ctx.name(), "ws-decoder", newWebsocketDecoder());
    } else {
        if (p.get(HttpRequestEncoder.class) != null) {
            p.remove(HttpRequestEncoder.class);
        }
        p.replace(ctx.name(),
                "ws-decoder", newWebsocketDecoder());
    }
}
项目:xio    文件:Recipes.java   
public static List<ByteBuf> encodeRequest(DefaultFullHttpRequest request) {
  EmbeddedChannel channel = new EmbeddedChannel();

  channel.pipeline().addLast("http request encoder", new HttpRequestEncoder());
  channel.writeOutbound(request);
  return extractBuffers(channel);
}
项目:xio    文件:GentleSslHandlerUnitTest.java   
public static ByteBuf encodeRequest(HttpRequest request) {
  EmbeddedChannel channel = new EmbeddedChannel();

  channel.pipeline().addLast("http request encoder", new HttpRequestEncoder());
  channel.writeOutbound(request);
  channel.runPendingTasks();
  return channel.readOutbound();
}
项目:xio    文件:ClientCodecFunctionalTest.java   
@Before
public void setUp() {
  encoder = new ClientCodec();

  channel = new EmbeddedChannel();

  channel
      .pipeline()
      .addLast(new FrameLengthCodec())
      .addLast(new Encoder())
      // http encoder
      .addLast(new HttpRequestEncoder())
      .addLast(encoder);
}
项目:appdeck-android    文件:ProxyToServerConnection.java   
/**
 * Initialize our {@link ChannelPipeline}.
 * 
 * @param pipeline
 * @param httpRequest
 */
private void initChannelPipeline(ChannelPipeline pipeline,
        HttpRequest httpRequest) {
    pipeline.addLast("bytesReadMonitor", bytesReadMonitor);
    pipeline.addLast("decoder", new HeadAwareHttpResponseDecoder(
            8192,
            8192 * 2,
            8192 * 2));
    pipeline.addLast("responseReadMonitor", responseReadMonitor);

    if (!ProxyUtils.isCONNECT(httpRequest)) {
        // Enable aggregation for filtering if necessary
        int numberOfBytesToBuffer = proxyServer.getFiltersSource()
                .getMaximumResponseBufferSizeInBytes();
        if (numberOfBytesToBuffer > 0) {
            aggregateContentForFiltering(pipeline, numberOfBytesToBuffer);
        }
    }

    pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor);
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("requestWrittenMonitor", requestWrittenMonitor);

    // Set idle timeout
    pipeline.addLast(
            "idle",
            new IdleStateHandler(0, 0, proxyServer
                    .getIdleConnectionTimeout()));

    pipeline.addLast("handler", this);
}
项目:appdeck-android    文件:ProxyToServerConnection.java   
/**
 * Initialize our {@link ChannelPipeline}.
 * 
 * @param pipeline
 * @param httpRequest
 */
private void initChannelPipeline(ChannelPipeline pipeline,
        HttpRequest httpRequest) {
    pipeline.addLast("bytesReadMonitor", bytesReadMonitor);
    pipeline.addLast("decoder", new HeadAwareHttpResponseDecoder(
            8192,
            8192 * 2,
            8192 * 2));
    pipeline.addLast("responseReadMonitor", responseReadMonitor);

    if (!ProxyUtils.isCONNECT(httpRequest)) {
        // Enable aggregation for filtering if necessary
        int numberOfBytesToBuffer = proxyServer.getFiltersSource()
                .getMaximumResponseBufferSizeInBytes();
        if (numberOfBytesToBuffer > 0) {
            aggregateContentForFiltering(pipeline, numberOfBytesToBuffer);
        }
    }

    pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor);
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("requestWrittenMonitor", requestWrittenMonitor);

    // Set idle timeout
    pipeline.addLast(
            "idle",
            new IdleStateHandler(0, 0, proxyServer
                    .getIdleConnectionTimeout()));

    pipeline.addLast("handler", this);
}
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketClientHandshaker.java   
/**
 * Begins the opening handshake
 *
 * @param channel
 *            Channel
 * @param promise
 *            the {@link ChannelPromise} to be notified when the opening handshake is sent
 */
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
    FullHttpRequest request =  newHandshakeRequest();

    HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
    if (decoder == null) {
        HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
        if (codec == null) {
           promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                   "a HttpResponseDecoder or HttpClientCodec"));
           return promise;
        }
    }

    channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = future.channel().pipeline();
                ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                if (ctx == null) {
                    ctx = p.context(HttpClientCodec.class);
                }
                if (ctx == null) {
                    promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                            "a HttpRequestEncoder or HttpClientCodec"));
                    return;
                }
                p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());

                promise.setSuccess();
            } else {
                promise.setFailure(future.cause());
            }
        }
    });
    return promise;
}
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketClientHandshaker.java   
/**
 * 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);
    setActualSubprotocol(response.headers().get(HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL));
    setHandshakeComplete();

    ChannelPipeline p = channel.pipeline();
    // Remove decompressor from pipeline if its in use
    HttpContentDecompressor decompressor = p.get(HttpContentDecompressor.class);
    if (decompressor != null) {
        p.remove(decompressor);
    }

    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");
        }
        p.replace(ctx.name(), "ws-decoder", newWebsocketDecoder());
    } else {
        if (p.get(HttpRequestEncoder.class) != null) {
            p.remove(HttpRequestEncoder.class);
        }
        p.replace(ctx.name(),
                "ws-decoder", newWebsocketDecoder());
    }
}
项目:BrowserPush    文件:EventSource.java   
void createBootstrap() {
    bootstrap = new Bootstrap();
    bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();

                    //Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, 
                    //a single U+000A LINE FEED (LF) character, 
                    //or a single U+000D CARRIAGE RETURN (CR) character.
                    p.addLast(new HttpRequestEncoder(),
                              new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, new ByteBuf[] {
                                      Unpooled.wrappedBuffer(new byte[]{'\r', '\n'}),
                                      Unpooled.wrappedBuffer(new byte[] { '\n' }),
                                      Unpooled.wrappedBuffer(new byte[] { '\r' })}),
                              new StringDecoder(CharsetUtil.UTF_8),
                              handler);
                }
            });

    int port = uri.getPort();
    if(port <= 0) {
        String protocol = uri.getScheme();
        if ("http".equals(protocol)) {
            port = 80;
        } else {
            port = 443;
        }
    }
    bootstrap.connect(uri.getHost(), port);
}
项目:shortcircuit-proxy    文件:NettyProxyFrontendHandler.java   
private void initOutboundChannel(final ChannelHandlerContext ctx, final HttpRequest request,
        SocketAddress address) {
    final Channel inboundChannel = ctx.channel();
    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop());
    b.channel(ctx.channel().getClass());
    b.handler(new NettyProxyBackendHandler(inboundChannel));
    b.option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(address);
    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = outboundChannel.pipeline();
                p.addLast(new LoggingHandler(NettyProxyBackendHandler.class), //
                        new HttpRequestEncoder());

                // There is no connection caching at the moment.
                // RFC 2616 HTTP/1.1 section 14.10 says:
                // HTTP/1.1 applications that do not support persistent
                // connections MUST include the "close" connection
                // option
                // in every message
                HttpUtil.setKeepAlive(request, false);

                // URLConnection rejects if the proxied URL won't start
                // with the query, see RFC 7230 section 5.3.1.
                String adjustedUri = ProxyUtils.stripHost(request.uri());
                request.setUri(adjustedUri);

                writeOutbound(ctx, request);
            } else {
                // Close the connection if the connection attempt has
                // failed.
                inboundChannel.close();
            }
        }
    });
}
项目:zbus    文件:MqClient.java   
private void buildSupport(ServerAddress serverAddress, final EventLoop loop, long heartbeatInterval){
    this.token = serverAddress.getToken();
    if(serverAddress.server != null){
        support = new InProcClient<Message, Message>(serverAddress.server);
        return;
    } 
    String address = serverAddress.address;
    if(address == null){
        throw new IllegalArgumentException("ServerAddress missing address property");
    }

    if (address.startsWith("ipc://")) {
        throw new IllegalArgumentException("IPC not implemented yet!");
        //TODO IPC client support
    }

    //default to TCP 
    if(address.startsWith("tcp://")){
        serverAddress.address = address.substring("tcp://".length());
    }

    TcpClient<Message, Message> tcp = new TcpClient<Message, Message>(serverAddress, loop);
    support = tcp;
    tcp.codec(new CodecInitializer() {
        @Override
        public void initPipeline(List<ChannelHandler> p) {
            p.add(new HttpRequestEncoder()); 
            p.add(new HttpResponseDecoder());  
            p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
            p.add(new io.zbus.transport.http.MessageCodec());
            p.add(new io.zbus.mq.MessageCodec());
        }
    }); 

    tcp.startHeartbeat(heartbeatInterval, new HeartbeatMessageBuilder<Message>() { 
        @Override
        public Message build() { 
            Message hbt = new Message();
            hbt.setCommand(Message.HEARTBEAT);
            return hbt;
        }
    });  
}
项目:netty4.0.27Learn    文件:WebSocketClientHandshaker.java   
/**
 * 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(HttpHeaders.Names.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;
        setActualSubprotocol(expectedSubprotocol); // null or "" - we echo what the user requested
    } else if (!expectedProtocol.isEmpty() && receivedProtocol != null && !receivedProtocol.isEmpty()) {
        // We require a subprotocol and received one -> verify it
        for (String protocol : StringUtil.split(expectedSubprotocol, ',')) {
            if (protocol.trim().equals(receivedProtocol)) {
                protocolValid = true;
                setActualSubprotocol(receivedProtocol);
                break;
            }
        }
    } // else mixed cases - which are all errors

    if (!protocolValid) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid subprotocol. Actual: %s. Expected one of: %s",
                receivedProtocol, expectedSubprotocol));
    }

    setHandshakeComplete();

    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");
        }
        p.replace(ctx.name(), "ws-decoder", newWebsocketDecoder());
    } else {
        if (p.get(HttpRequestEncoder.class) != null) {
            p.remove(HttpRequestEncoder.class);
        }
        p.replace(ctx.name(),
                "ws-decoder", newWebsocketDecoder());
    }
}