HttpServletRequest获取body中的参数
时间: 2023-10-14 18:18:58 浏览: 144
[ vue ] axios 发送 POST 请求,后端不能通过 HttpServletRequest 获取参数
要获取HTTP请求中的请求体(body)中的参数,可以使用HttpServletRequest对象的getInputStream()方法和BufferedReader对象的readLine()方法。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.http.HttpServletRequest;
public class RequestBodyReader {
public static String read(HttpServletRequest request) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) != -1) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
return stringBuilder.toString();
}
}
```
可以使用如下代码调用该方法:
```java
String body = RequestBodyReader.read(request);
```
其中,request是HttpServletRequest对象。返回的body即为请求体中的参数。
阅读全文