Springboot 同时支持GET和POST请求

根据大佬博客,集成的工具类:



import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


public class HttpServletRequestUtils {

    /**
     * 解析HttpServletRequest参数
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static Map getRequestParams(HttpServletRequest request) throws IOException {
        String method = request.getMethod();
        if ("GET".equals(method)) {
            return getHttpServletRequestFormParams(request);
        }
        if ("POST".equals(method)) {
            return getHttpServletRequestJsonParams(request);
        }
        return new HashMap<>();
    }

    /**
     * @param request
     * @return java.util.Map
     * @description: 获取 HttpServletRequest 参数  表单参数
     * GET:地址栏中直接给出参数:http://localhost/param/ParamServlet?p1=v1&p2=v2;
     * POST:表单
     * @date: 2021/9/24
     */
    public static Map getHttpServletRequestFormParams(HttpServletRequest request) {
        Map paramMap = new HashMap<>();
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String[] parameterValues = request.getParameterValues(paramName);
            if (1 == parameterValues.length) {
                String paramValue = parameterValues[0];
                paramMap.put(paramName, paramValue);
            }
        }

        return paramMap;
    }

    /**
     * @param request
     * @return java.util.Map
     * @description: 解析HttpServletRequest参数  json格式
     * POST:JSON格式
     * @date: 2021/9/24
     */
    public static Map getHttpServletRequestJsonParams(HttpServletRequest request) throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength <= 0) {
            return new HashMap<>();
        }
        byte[] buffer = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {
            int readLen = request.getInputStream().read(buffer, i, contentLength - i);
            if (-1 == readLen) {
                break;
            }
            i += readLen;
        }
        Map maps = (Map) JSON.parse(buffer);
        return maps;
    }

}

最后的调用方式:

post  传json: 

url:localhost:8100/xxx/yyy/sendMssage

post:
{
    "companyName":"xcxxxx公司",
    "telePhone":"11111111",
    "msgContext":"内容111test 1"
}

get 请求:

localhost:8100/xxx/yyy/sendMssage?companyName=xxx分公司&telePhone=2222222&msgContext=内容fff test 1

参考博客:

get和表单post方式:

Springboot 定义接口方法同时支持GET和POST请求_真空零点能的博客-CSDN博客

post 的json解析:

HttpServletRequest 接收并解析获取JSON数据_weixin_34405925的博客-CSDN博客

你可能感兴趣的:(springboot,http,java,spring)