Java获取访问请求的参数列表信息

😂 这篇文章最后更新于719天前,您需要注意相关的内容是否还可用。

所需依赖:

servlet-api
    @RequestMapping("/getPost")
    public String getJson(HttpServletRequest request) throws IOException {
        String sret = null;
        String ContentType = "";

        ContentType = request.getHeader("Content-Type");
        if (ContentType.equalsIgnoreCase("application/x-www-form-urlencoded")) {
//            这里Map中的泛型最好写上 方便idea自动生成entries
            Map<String, String[]> params = request.getParameterMap();
//            Set泛型写上才可以遍历entries
            Set<Map.Entry<String, String[]>> entries = params.entrySet();
            String queryString = "";
            for (String key : params.keySet()) {
                String[] values = params.get(key);
                for (int i = 0; i < values.length; i++) {
                    String value = values[i];
                    queryString += key + "=" + value + "&";
                }
            }

            if (queryString.length() > 1) {
                // 去掉最后一个空格
                queryString = queryString.substring(0, queryString.length() - 1);
            }

            sret = queryString;

        } else if (ContentType.equalsIgnoreCase("multipart/form-data")) {
            try {
                StringBuffer info = new StringBuffer();
                ServletInputStream in = request.getInputStream();
                BufferedInputStream buf = new BufferedInputStream(in);
                byte[] buffer = new byte[1024];
                int iRead;
                while ((iRead = buf.read(buffer)) != -1) {
                    info.append(new String(buffer, 0, iRead, "UTF-8"));
                    sret = info.toString();
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {

        }

        return sret;
    }

    @RequestMapping("/get")
    public static String getGetParam(HttpServletRequest request) {
        String sret = null;
        String queryString = null;
//只能获取get参数
        queryString = request.getQueryString();
        sret = queryString;
        return sret;
    }