Netty 获取Get,POST数据

Netty Http请求帮助类

package com.TKW.nettyServer;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import io.netty.util.CharsetUtil;

import com.TKW.Utils.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpRequestParser {

    public static Map<String, Object> readParams(FullHttpRequest request){
        if(request.method() == HttpMethod.GET){
            return readGetParams(request);
        }
        else if(request.method() == HttpMethod.POST){
            return readPostParams(request);
        }
        else{
            return  null;
        }
    }
    /**
     * 读取GET方法的参数
     * @param request
     * @return
     */
    public static Map<String, Object> readGetParams(FullHttpRequest request) {

        if (request.method() == HttpMethod.GET) {

            Map<String, Object> paramMap = new HashMap<>();

            QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
            decoder.parameters().entrySet().forEach(entry -> {
                paramMap.put(entry.getKey(), entry.getValue().get(0));
            });

            return paramMap;
        }

        return null;
    }


    /**
     * 读取POST方法的表单参数
     *
     * @param request
     * @return 返回一个Map
     */
    public static Map<String, Object> readPostParams(FullHttpRequest request) {

        if (request.method() == HttpMethod.POST) {
            String contentType = request.headers().get("Content-Type").trim().toLowerCase();

            if (contentType.contains("x-www-form-urlencoded")) {
                Map<String, Object> paramMap = new HashMap<>();

                HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);

                List<InterfaceHttpData> parmList = decoder.getBodyHttpDatas();

                for (InterfaceHttpData parm : parmList) {
                    if (parm.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                        MemoryAttribute data = (MemoryAttribute) parm;
                        paramMap.put(data.getName(), data.getValue());
                    }
                }

                return paramMap;
            }
            else if(contentType.contains("json")){
                ByteBuf content = request.content();
                String msg = content.toString(CharsetUtil.UTF_8);

                Map<String, Object> paramMap = GsonUtils.fromJson(msg, Map.class);

                return paramMap;

            }
        }

        return null;

    }

}

使用Main函数

配合netty服务器
HttpServer:

package com.TKW.nettyServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;


public class HttpServer {
    public static void main(String[] args) throws Exception {
        HttpServer server = new HttpServer();
        server.bind(10110);
    }

    private void bind(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 512)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                          ch.pipeline().addLast(new HttpServerCodec());
                          ch.pipeline().addLast(new HttpObjectAggregator(65536));
                          ch.pipeline().addLast(new ParseRequestHandler());
                          /*ch.pipeline().addLast(new OozieRequestHandler());*/
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("服务端打开端口: "+ port);
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

ParseRequestHandler

通过工具类转换成Map类

public class ParseRequestHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
        HttpRequestParser httpRequestParser = new HttpRequestParser();
       Map<String, Object> stringObjectMap = httpRequestParser.readParams(fullHttpRequest);
         /*int i = judgeGetOrPost(stringObjectMap);
        Object message = getMessage(i);
        Object response = response(message);
        ctx.writeAndFlush(response);*/
    }

测试:

  1. Get方法直接将参数加到url中;
    在这里插入图片描述
  2. Post方法
    选择x-www-from-urlencode(再加key和value数据)
    在这里插入图片描述
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值