Netty--Http请求处理

1 这几天在看Netty权威指南,代码敲了一下,就当做个笔记吧。

/**
 * Http服务端
 * @author Tang
 * 2018年5月13日
 */
public class HttpServer {

	public void run(String url,Integer port) {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workerGroup);
		bootstrap.channel(NioServerSocketChannel.class);
		bootstrap.childHandler(new ChannelInitializer<Channel>() {
			@Override
			protected void initChannel(Channel ch) throws Exception {
				ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
				ch.pipeline().addLast("http-aggregator",
						new HttpObjectAggregator(65536));
				ch.pipeline()
						.addLast("http-encoder", new HttpResponseEncoder());
				ch.pipeline()
						.addLast("http-chunked", new ChunkedWriteHandler());
				ch.pipeline().addLast("http-handler", new HttpServerHandler());
			}
		});

		try {
			ChannelFuture channelFuture = bootstrap.bind(url, port).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) {
		new HttpServer().run("127.0.0.1",8001);
	}
}

业务处理逻辑:

public class HttpServerHandler extends
		SimpleChannelInboundHandler<FullHttpRequest> {

	@Override
	protected void messageReceived(ChannelHandlerContext ctx,
			FullHttpRequest fullHttpRequest) throws Exception {
		// 构造返回数据
		JSONObject jsonRootObj = new JSONObject();
		JSONObject jsonUserInfo = new JSONObject();
		jsonUserInfo.put("id", 1);
		jsonUserInfo.put("name", "张三");
		jsonUserInfo.put("password", "123");
		jsonRootObj.put("userInfo", jsonUserInfo);
		// 获取传递的数据
		Map<String, Object> params = getParamsFromChannel(ctx, fullHttpRequest);
		jsonRootObj.put("params", params);

		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
		response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
		StringBuilder bufRespose = new StringBuilder();
		bufRespose.append(jsonRootObj.toJSONString());
		ByteBuf buffer = Unpooled.copiedBuffer(bufRespose, CharsetUtil.UTF_8);
		response.content().writeBytes(buffer);
		buffer.release();
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}

	/**
	 * 获取传递的参数
	 * 
	 * @param ctx
	 * @param fullHttpRequest
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static Map<String, Object> getParamsFromChannel(
			ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest)
			throws UnsupportedEncodingException {
		HttpHeaders headers = fullHttpRequest.headers();
		String strContentType = headers.get("Content-Type").trim();
		System.out.println("ContentType:" + strContentType);
		Map<String, Object> mapReturnData = new HashMap<String, Object>();
		if (fullHttpRequest.getMethod() == HttpMethod.GET) {
			// 处理get请求
			QueryStringDecoder decoder = new QueryStringDecoder(
					fullHttpRequest.getUri());
			Map<String, List<String>> parame = decoder.parameters();
			for (Entry<String, List<String>> entry : parame.entrySet()) {
				mapReturnData.put(entry.getKey(), entry.getValue().get(0));
			}
			System.out.println("GET方式:" + parame.toString());
		} else if (fullHttpRequest.getMethod() == HttpMethod.POST) {
			// 处理POST请求
			if (strContentType.contains("x-www-form-urlencoded")) {
				HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(
						new DefaultHttpDataFactory(false), fullHttpRequest);
				List<InterfaceHttpData> postData = decoder.getBodyHttpDatas();
				for (InterfaceHttpData data : postData) {
					if (data.getHttpDataType() == HttpDataType.Attribute) {
						MemoryAttribute attribute = (MemoryAttribute) data;
						mapReturnData.put(attribute.getName(),
								attribute.getValue());
					}
				}
			} else if (strContentType.contains("application/json")) {
				// 解析json数据
				ByteBuf content = fullHttpRequest.content();
				byte[] reqContent = new byte[content.readableBytes()];
				content.readBytes(reqContent);
				String strContent = new String(reqContent, "UTF-8");
				System.out.println("接收到的消息" + strContent);
				JSONObject jsonParamRoot = JSONObject.parseObject(strContent);
				for (String key : jsonParamRoot.keySet()) {
					mapReturnData.put(key, jsonParamRoot.get(key));
				}
			} else {
				FullHttpResponse response = new DefaultFullHttpResponse(
						HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
				ctx.writeAndFlush(response).addListener(
						ChannelFutureListener.CLOSE);
			}
			System.out.println("POST方式:" + mapReturnData.toString());
		}
		return mapReturnData;
	}
}

支持Get和PostContentType为application/json、x-www-form-urlencoded的处理。
用Postman亲测无问题。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值