Java使用Netty消息聚合器實現Http響應聚合功能

public class SendRequest extends Thread{
	
	private String host;
	private int port;
	private String url;
	
	SendRequest(String host,int port, String url){
		this.host = host;
		this.port = port;
		this.url = url;
	}
	
	public void run() {
		sendRequest(host,port, url);
	}

	public void sendRequest(String host,int port, String url) {
		
		
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							//socketChannel.pipeline().addLast(new HttpRequestEncoder());// 客戶端對發送的httpRequest進行編碼
							//socketChannel.pipeline().addLast(new HttpResponseDecoder());// 客戶端需要對服務端返回的httpresopnse解碼
							socketChannel.pipeline().addLast("codec", new HttpClientCodec());
							socketChannel.pipeline().addLast("httpAggregator",new HttpObjectAggregator(512*1024)); // http 消息聚合器 
							socketChannel.pipeline().addLast(new GetResponse());
						}
						
					});

			DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url);
            // 構建http請求
            request.headers().set(HttpHeaderNames.HOST, host);
            request.headers().set(HttpHeaderNames.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0");
            request.headers().set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            request.headers().set(HttpHeaderNames.ACCEPT_LANGUAGE, "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
            request.headers().set(HttpHeaderNames.CONNECTION, "close");
			
			
			
			Channel channel = bootstrap.connect(host,port).sync().channel();

			// send request
			channel.writeAndFlush(request).sync();
			channel.closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			workerGroup.shutdownGracefully();
		}
		
	}

	// *** 獲取原本的response數據 ***
	private class GetResponse extends ChannelInboundHandlerAdapter {
		
		private HttpResponse response;
		private HttpContent content;
		
		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

			boolean flag = true;
			
			//匹配響應請求
			if (msg instanceof HttpResponse) {
				flag = false;
				//*** 將response保存到成員變量中 ***
				this.response = (HttpResponse) msg;
	        }
			if (msg instanceof HttpContent) {
				flag = false;
				//*** 將content保存到成員變量中 ***
				this.content = (HttpContent) msg;
	        }
			if(flag) {
				System.out.println("!!!!! 沒匹配到 !!!!!");
			}
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章