Tuesday, November 1, 2016

Creating a Mock Service to return HTTP Status Code with Custom Status Code Description using Tomcat / Servlet

In some cases, we may need to setup a mock service to return HTTP status codes with custom messages. You can follow the below to achieve this.


The Sample Servlet


package com.custom;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CustomStatus
 */
public class CustomStatus extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CustomStatus() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  response.setContentType("text/plain");
  response.setHeader("FROM", "AJANTH");
  if(request.getParameter("statusToReturn").equals("4001")){ 
   
   response.setStatus(400, "Invalid Request Parameters");
   
  }else if(request.getParameter("statusToReturn").equals("4002")){ 
   
   response.setStatus(400, "Invalid Request for Bad Gateway");   
  } 
  
  response.getWriter().write("Test From BackEND");
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

}


Configuration Need to do at Tomcat


In TOMCAT_HOME/conf/catalina.properties add the below lines:

org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER = true

Now when you send request through SOAP UI, you will see the below, where the header appended with our custom message.






1 comment:

  1. Thank you for the detailed guide on creating a mock service to return custom HTTP status code with descriptions. Your step-by-step instructions and code examples have been invaluable for understanding how to simulate different server responses effectively. This tutorial not only enhances my development skills but also provides a practical approach to testing and handling various scenarios in web applications. Your expertise is greatly appreciated in simplifying this process for developers.

    ReplyDelete