• Home
  • How to get response body from servletresponse in spring boot filter? – Java

How to get response body from servletresponse in spring boot filter? – Java

To get the response body from a ServletResponse object in Spring Boot, you can use the following method:

  1. First, you will need to get the ServletResponse object as an instance of HttpServletResponse. You can do this by casting the ServletResponse object to HttpServletResponse.
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
  1. Next, you can use the getOutputStream() method of the HttpServletResponse object to get an instance of ServletOutputStream.
ServletOutputStream outputStream = httpResponse.getOutputStream();
  1. You can then use the toByteArray() method of the ServletOutputStream to get the response body as a byte array.
byte[] responseBody = outputStream.toByteArray();
  1. If you want to convert the response body to a string, you can use the new String(byte[]) constructor to create a string from the byte array.
String responseBodyString = new String(responseBody);