天天看點

HttpServletRequest 接收并解析擷取JSON資料

最近在弄Security權限時遇到attemptAuthentication接口接收登入參數的時候隻能用request,但是現在很多項目都是已經使用前後端分離的開發模式了

像以往我們在Controller的時候處理json資料轉換隻需要标注@RequestBody注解即可.

有問題就要解決,打開debug找了一下request的字段内容,并沒有發現我所需要的Json資料,一時比較辣手,最後不得不面向Google程式設計了.

以下是工具類

public class GetRequestJsonUtils {
    public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
        String json = getRequestJsonString(request);
        return JSONObject.parseObject(json);
    }
    /***
     * 擷取 request 中 json 字元串的内容
     *
     * @param request
     * @return : <code>byte[]</code>
     * @throws IOException
     */
    public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
            return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
            // POST
        } else {
            return getRequestPostStr(request);
        }
    }

    /**
     * 描述:擷取 post 請求的 byte[] 數組
     * <pre>
     * 舉例:
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        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;
    }

    /**
     * 描述:擷取 post 請求内容
     * <pre>
     * 舉例:
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }


}           

最後我們隻需要把request傳入GetRequestJsonUtils傳回一個JSONObject 對象.

JSONObject json = GetRequestJsonUtils.getRequestJsonObject(request);
String username = json.getString(usernameParameter);
String password = json.getString(passwordParameter);           

原文位址:

https://blog.csdn.net/tengdazhang770960436/article/details/50149061