在处理http Keep-Alive连接时,如何使用netty将响应映射到请求URL

时间:2015-10-12 09:04:03

标签: http netty keep-alive

我想读取支持http 1.1 keep-live的同一站点的url列表。

我尝试使用netty来做这件事并且有效。

但是当我收到回复时,我无法确定它是针对哪个网址。

如何从下面的方法messageReceived获取请求网址

 public static void main(String[] args) throws InterruptedException, URISyntaxException {
    String host = "localhost";
    int port = 8080;
    String[] paths = new String[]{"1.html", "2.html", "3.html"};
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(group)
            .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 HttpContentDecompressor());
                    p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
                        @Override
                        protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                            if (msg instanceof HttpContent) {
                                HttpContent content = (HttpContent) msg;
                                System.out.println("response from url ?:" + content.content().toString());
                            }
                        }
                    });
                }
            });

    Channel ch = b.connect(host, port).sync().channel();
    for (String path : paths) {
        HttpRequest request = new DefaultFullHttpRequest(
                HttpVersion.HTTP_1_1, HttpMethod.GET, path);
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
        ch.writeAndFlush(request);
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

 p.addLast(new SimpleChannelInboundHandler<Object>() {
     @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg) {
         if (msg instanceof HttpRequest) {
            System.out.println("I'm HttpRequest");

            FullHttpRequest req = (FullHttpRequest) msg;

            if (HttpHeaders.is100ContinueExpected(req)) {
                 ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
            }

            System.out.println("response from url ?:" + req.getUri());
            ByteBuf content = req.content();
         }
     }
 });

不知道你使用的是什么版本的netty。如果是5.0+,请将channelRead重命名为messageReceived