我想阅读url到支持http 1.1的同一网站的列表。
我试着用netty来做这件事,它工作。
但是当我得到响应时,我不能确定它是哪个url。
如何从下面的messagerreceived方法获得请求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