Netty4.0的DefaultHttpRequest与FullHttpRequest

本人用netty4.0做Http服务器模块时,出现了一个Bug,从平台发送过来的充值请求接收不到,充值请求是Post方式,自己写了个post工具模拟充值请求,发现:能收到HttpRequest,但收不到HttpContent。

消息分发器代码:

	protected void channelRead0(ChannelHandlerContext ctx, Object data)
			throws Exception {
if (data instanceof HttpRequest) {
.....
}
else if(data instanceof HttpContent){
....
}
}

这是以前没出问题时的部分代码,Post请求是分两次收到的,一次是HttpRequest,只有Http 协议头,一次是HttpContent,内容是data form数据。


消息处理链代码:

		ChannelPipeline pipeline = channel.pipeline();
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(HANDLER);

之后修改了消息处理链的代码,因为不能响应太长数据消息:

	@Override
	protected void initChannel(SocketChannel channel) throws Exception {
		ChannelPipeline pipeline = channel.pipeline();
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast( new HttpObjectAggregator(65536));
		pipeline.addLast(new ChunkedWriteHandler());
//		pipeline.addLast(new HttpRequestDecoder());
		pipeline.addLast(HANDLER);

添加HttpObjectAggregator和ChunkedWriteHandler,结果就出现了这个问题

相应的分发器代码也要改

	protected void channelRead0(ChannelHandlerContext ctx, Object data)
			throws Exception {
		//DefaultHttpRequest
		//FullHttpRequest
		if(data instanceof FullHttpRequest){
			FullHttpRequest fhr = (FullHttpRequest)data;
			String uri = fhr.getUri();
			int platType = -1;
			int action = 0;
			if(uri.startsWith("/exchange")){
				platType = PlatformTypes.QIHOO;
				action = PlatformManager.ACTION_EXCHANGE;
				int len = fhr.content().readableBytes();
				if(len > 0){
					byte[] content = new byte[len];
					fhr.content().readBytes(content);
					String contentStr = new String(content, "UTF-8");
					Map paramMap = HttpUtil.url2Map(contentStr);
					PlatformManager.getInstance().doAction(platType, action, paramMap, ctx.channel());
				}
				return;
			}
		}

FullHttpRequest的协议头和Form数据是在一起的,不用分开读,之前分开接收的是DefaultHttpRequest与HttpContent,FullHttpRequest把两者合在一起了,Netty不熟悉就是容易出错。

你可能感兴趣的:(netty)