SpringMVC接收Postman post json数据

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

final Map allParams = Maps.newHashMap();
final Enumeration 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 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;
    }

转载于:https://www.cnblogs.com/umgsai/p/9556684.html

你可能感兴趣的:(SpringMVC接收Postman post json数据)