zoukankan      html  css  js  c++  java
  • SpringMVC接收Postman post json数据

    当postman向服务端post数据时,一般要求在body里已x-www-form-urlencoded格式写成key-value的形式。服务端通过以下代码可以取到参数

    final Map<String, String> allParams = Maps.newHashMap();
    final Enumeration<String> paramEnum = request.getParameterNames();
    while (paramEnum.hasMoreElements()) {
        String parameterName = paramEnum.nextElement();
        allParams.put(parameterName, request.getParameter(parameterName));
    }
    

    但是当post向服务端post raw格式数据时,以上方式就取不到参数列表了。此时用以下方式取参数

        String postString = getRequestPostString(request);
        if (!StringUtil.isEmpty(postString)){
            JSONObject jsonObject = JSON.parseObject(postString);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof JSONArray) {
                    allParams.put(key, JSON.toJSONString(value));
                } else {
                    allParams.put(key, String.valueOf(value));
                }
            }
        }
    
        private String getRequestPostString(HttpServletRequest request) throws IOException {
            byte buffer[] = getRequestPostBytes(request);
            String charEncoding = request.getCharacterEncoding();
            if (charEncoding == null) {
                charEncoding = Charset.defaultCharset().name();
            }
            return new String(buffer, charEncoding);
        }
    
    
        private byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
            int contentLength = request.getContentLength();
            /*当无请求参数时,request.getContentLength()返回-1 */
            if (contentLength < 0) {
                return null;
            }
            byte buffer[] = new byte[contentLength];
            for (int i = 0; i < contentLength;) {
    
                int readlen = request.getInputStream().read(buffer, i, contentLength - i);
                if (readlen == -1) {
                    break;
                }
                i += readlen;
            }
            return buffer;
        }
    
  • 相关阅读:
    Dev GridControl 小结3
    一个web应用的诞生(9)--回到用户
    一个web应用的诞生(8)--博文发布
    一个web应用的诞生(7)--结构调整
    一个web应用的诞生(6)--用户账户
    一个web应用的诞生(5)--数据表单
    一个web应用的诞生(4)--数据存储
    一个web应用的诞生(3)--美化一下
    一个web应用的诞生(2)--使用模板
    一个web应用的诞生(1)--初识flask
  • 原文地址:https://www.cnblogs.com/umgsai/p/9556684.html
Copyright © 2011-2022 走看看