How to get response body from httpservletresponse

To get the response body from HttpServletResponse in Java, you can follow these steps:

  1. Get the PrintWriter object of the HttpServletResponse.
  2. Use the PrintWriter object to write the response content.
  3. Close the PrintWriter to commit the response and send it back to the client.
    
      // Get the PrintWriter object from HttpServletResponse
      PrintWriter writer = response.getWriter();
      
      // Write response content to the PrintWriter
      writer.println("This is the response body");
      
      // Close the PrintWriter
      writer.close();
    
  

Here’s a complete example:

    
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;
      import java.io.PrintWriter;

      public class MyServlet extends HttpServlet {
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

              // Set the content type of the response
              response.setContentType("text/html");

              // Get the PrintWriter object from HttpServletResponse
              PrintWriter writer = response.getWriter();

              // Write response content to the PrintWriter
              writer.println("This is the response body");

              // Close the PrintWriter
              writer.close();
          }
      }
    
  

In this example, we’re extending the HttpServlet class and overriding the doGet() method to handle GET requests. The response content type is set to “text/html”. We obtain the PrintWriter object from the HttpServletResponse and use it to write “This is the response body” to the response.

Once the PrintWriter is closed, the response is committed and sent back to the client.

Leave a comment