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;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM