本文介绍了从 HttpServletRequest 获取 POST 请求体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 HttpServletRequest 对象中获取整个主体.

I am trying to get the whole body from the HttpServletRequest object.

我正在跟踪的代码如下所示:

The code I am following looks like this:

if ( request.getMethod().equals("POST") )
{
    StringBuffer sb = new StringBuffer();
    BufferedReader bufferedReader = null;
    String content = "";

    try {
        //InputStream inputStream = request.getInputStream();
        //inputStream.available();
        //if (inputStream != null) {
        bufferedReader =  request.getReader() ; //new BufferedReader(new InputStreamReader(inputStream));
        char[] charBuffer = new char[128];
        int bytesRead;
        while ( (bytesRead = bufferedReader.read(charBuffer)) != -1 ) {
            sb.append(charBuffer, 0, bytesRead);
        }
        //} else {
        //        sb.append("");
        //}

    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }

    test = sb.toString();
}

我正在使用 curl 和 wget 测试功能,如下所示:

and I am testing the functionality with curl and wget as follows:

curl --header "MD5: abcd" -F "[email protected] http://localhost:8080/abcd.html"

wget --header="MD5: abcd" --post-data='{"imei":"351553012623446","hni":"310150","wdp":false}' http://localhost:8080/abcd.html"

但是 while ( (bytesRead = bufferedReader.read(charBuffer)) != -1 ) 没有返回任何东西,所以我没有在 StringBuffer 上附加任何内容.

But the while ( (bytesRead = bufferedReader.read(charBuffer)) != -1 ) does not return anything, and so I get nothing appended on StringBuffer.

推荐答案

在 Java 8 中,你可以用更简单和干净的方式来做到:

In Java 8, you can do it in a simpler and clean way :

if ("POST".equalsIgnoreCase(request.getMethod()))
{
   test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}

这篇关于从 HttpServletRequest 获取 POST 请求体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:40