在Java servlet中從POST請求獲取請求負載


Answers

String payloadRequest = getBody(request);

使用這種方法

public static String getBody(HttpServletRequest request) throws IOException {

    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;

    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }

    body = stringBuilder.toString();
    return body;
}
Question

我有一個向我的Java servlet發送POST請求的JavaScript庫,但是在doPost方法中,我似乎無法獲取請求有效內容的內容。 在Chrome開發人員工具中,所有內容位於“標題”選項卡的“請求負載”部分,並且內容在那裡,並且我知道doPost方法正在接收POST,但它只是空白。

對於HttpServletRequest對象,我可以通過什麼方式獲取請求負載中的數據?

執行request.getParameter()request.getAttributes()都沒有數據




如果在Java 8中正文的內容是一個字符串,你可以這樣做:

String body = request.getReader().lines().collect(Collectors.joining());




你只需要

request.getParameterMap()

獲取POST和GET參數。

該方法返回一個Map<String,String[]>

您可以閱讀地圖依據中的參數

Map<String, String[]> map = request.getParameterMap();
//Reading the Map
//Works for GET && POST Method
for(String paramName:map.keySet()) {
    String[] paramValues = map.get(paramName);

    //Get Values of Param Name
    for(String valueOfParam:paramValues) {
        //Output the Values
        System.out.println("Value of Param with Name "+paramName+": "+valueOfParam);
    }
}



Java 8流

String body = request.getReader().lines()
    .reduce("", (accumulator, actual) -> accumulator + actual);



Related