http 请求体 body原始报文 java怎么获取
时间: 2023-05-16 08:01:10 浏览: 801
在 Java 中,我们可以通过使用 Java 的 API 来获取 HTTP 请求体 body 原始报文。
首先,我们需要使用 Java 中的 Servlet API 提供的 HttpServletRequest 类来获取 HTTP 请求体。这个类中有一个 getInputStream() 方法,它返回一个 InputStream 对象,这个对象就是包含了 HTTP 请求体的原始报文。
使用这个 InputStream 对象,我们可以使用 Java IO 的相关类来读取 HTTP 请求体的原始报文。一般情况下,我们可以使用 InputStreamReader 和 BufferedReader 类来读取 HTTP 请求体的原始报文。
使用 InputStreamReader 类将 InputStream 转换为字符流,然后使用 BufferedReader 类来读取字符流中的文本内容。具体实现代码如下:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.http.HttpServletRequest;
public class HttpHelper {
public static String getRequestBody(HttpServletRequest request) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
```
以上代码中,我们实现了一个 HttpHelper 类,其中 getRequestBody() 方法就是用来获取 HTTP 请求体 body 原始报文的。我们传入一个 HttpServletRequest 对象,然后调用 getInputStream() 方法获取 InputStream 对象,并使用 BufferedReader 对象来读取 InputStream 中的内容,最终将读取到的内容返回为一个字符串。这样,我们就可以轻松地获取 HTTP 请求体 body 原始报文了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)