Netty 获取Get,POST数据

netty 专栏收录该内容
1 篇文章 0 订阅

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
    点赞
  • 1
    评论
  • 3
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

评论 1 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:游动-白 设计师:我叫白小胖 返回首页

打赏作者

汪汪思密达

继续努力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值