gpt4 book ai didi

java - 从 HttpServletRequest 获取 POST 请求正文

转载 作者:IT老高 更新时间:2023-10-28 11:44:15 25 4
gpt4 key购买 nike

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

我正在关注的代码如下所示:

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 测试功能,如下所示:

curl --header "MD5: abcd" -F "fileupload=@filename.txt 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 上附加任何内容。

最佳答案

在 Java 8 中,您可以用一种更简单、更简洁的方式来做到这一点:

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

关于java - 从 HttpServletRequest 获取 POST 请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com