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

How can map the response to the request url with netty when handle http Keep-Alive connections

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

我尝试使用 netty 来做这个并且它有效。

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

如何从下面的 messageReceived 方法中获取 请求 url

 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);
    }

试试这个:

 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.