spring boot如何查看body原始内容
时间: 2023-08-15 11:02:38 浏览: 79
在Spring Boot中,我们可以使用一些方法来查看请求body的原始内容。
一种方法是通过使用HttpServletRequest对象来获取请求的输入流,然后读取流中的内容。可以通过在Controller中注入HttpServletRequest对象并调用getInputStream方法来实现。例如:
```java
@RestController
public class MyController {
@RequestMapping(value = "/example", method = RequestMethod.POST)
public String getRequestBody(HttpServletRequest request) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
```
另一种方法是使用注解@RequestBody来获取原始的请求body内容。在Controller方法的参数上添加@RequestBody注解,Spring Boot会自动将请求body转换为对应的对象。如果想要获取原始内容,可以将方法参数设置为String类型。例如:
```java
@RestController
public class MyController {
@RequestMapping(value = "/example", method = RequestMethod.POST)
public String getRequestBody(@RequestBody String requestBody) {
return requestBody;
}
}
```
无论哪种方法,都可以让我们轻松地查看Spring Boot中请求body的原始内容。