欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpServletRequest获取GET POST JSON 请求数据

程序员文章站 2024-02-04 14:02:40
...

HttpServletRequest接收获取GET POST JSON 请求数据

GET请求数据获取:

public void get(HttpServletRequest request) throws IOException {
        String params = request.getQueryString();
    }

POST请求数据获取:

post请求数据需要从请求头中获取

public void post(HttpServletRequest request) throws IOException {
        Map<String, String[]> map = request.getParameterMap();
        Map<String, Object> params = new HashMap<String, Object>();
        int length;
        //将Map<String, String[]>转为普通map
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            length = entry.getValue().length;
            if (length == 1) {
                params.put(entry.getKey(), entry.getValue()[0]);
            } else if (length > 1) {
                params.put(entry.getKey(), entry.getValue());
            }
        }
    }

JSON请求数据获取:

通过InputStream流获取

public void json(HttpServletRequest request) throws IOException {
        BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            sb.append(inputStr);
        }
        System.out.println(sb.toString());
    }