无法从HttpServletRequest中获取内容

时间:2009-06-30 21:27:28

标签: java java-ee servlets

我正在尝试获取HttpServletRequest的内容。我正是这样做的:

// Extract the request content
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
String content = "";

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

content =  stringBuilder.toString();
System.out.println("Length: " + request.getContentLength());

字符串“content”为空。但是,最后一行显示

  

长度:53

这正是我期待的内容的长度。如果有帮助,这就是我触发这个servlet的方法:

wget --post-data='{"imei":"351553012623446","hni":"310150","wdp":false}' http://localhost:8080/test/forward

1 个答案:

答案 0 :(得分:2)

嗯,我终于找到了答案!事实证明,给予wget的“post-data”的值成为请求中参数的名称。换句话说,如果我在请求中获得第一个(也是唯一的)参数的参数名称,我将获得该值。提取它的代码很简单:

// Extract the post content from the request
@SuppressWarnings("unchecked")
Enumeration<String> paramEnum = request.getParameterNames();
paramEnum.hasMoreElements();
String postContent = (String) paramEnum.nextElement();

感谢大家的回复!