解析request请求中的body

一、使用getReader()获取body

 


 

/**
 * 从request中获取body 通过getReader()获取
 * @author syx
 * @param request
 */
 public static String getBodyStringByReader(HttpServletRequest request){
        BufferedReader bufferedReader = null;
        StringBuilder sb = new StringBuilder();
        try {
            bufferedReader = request.getReader();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bufferedReader!= null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

二、使用getInputStream()获取body


 

/**
 * 从request中获取body 通过inputStream获取
 * @author syx
 * @param request
 */
public static String getBodyStringByInputStream(HttpServletRequest request) {
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder sb = new StringBuilder();
        try {
            inputStream = request.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader!= null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }

 

三、两者的区别:

使用getInputStream() 可自行指定编码格式、

使用getReader()则默认使用body中的编码格式,如果找不到编码格式则默认使用ISO-8859-1

 

你可能感兴趣的:(java,servlet)