888
888

Reputation: 3396

Send POST request within the processRequest method of a servlet

I have a servlet which receives a parameter in the request, executes some operations, then it has to redirect (with a POST) to another server with some parameters in JSON (included the received parameter).

My code is:

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
                              throws ServletException, IOException {

    String par = request.getParameter("myParameter");

    String par2 = someStuff();

    JSONObject json = new JSONObject();

    json.put("myParameter", par);
    json.put("otherParameter", par2);

    response.setContentType("application/json");
    response.getWriter().write(json.toString());

    ...
}

I thougt to replace the dots with:

  1. The response.sendRedirect(...) method, but it's a GET request.

  2. A RequestDispatcher with the forward method, but I can't send requests to another container.

How can I send a POST request to another container with JSON parameters?

Upvotes: 1

Views: 11304

Answers (2)

Christopher Schultz
Christopher Schultz

Reputation: 20837

If you must be able to contact another server, you'll have to roll your own POST request. I would recommend using a library like Apache httpcomponents httpclient to do your dirty work. Then your code will look like this:

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {

  String par = request.getParameter("myParameter");

  String par2 = someStuff();

  JSONObject json = new JSONObject();

  json.put("myParameter", par);
  json.put("otherParameter", par2);

  HttpPost method = new HttpPost(new URI("https://host/service"));
  method.setHeader("Content-Type", "application/json");
  method.setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
  HttpParams params=message.getParams();
  HttpConnectionParams.setConnectionTimeout(params, timeout);
  HttpConnectionParams.setSoTimeout(params, timeout);
  HttpClient client = new DefaultHttpClient();
  HttpResponse response = client.execute(method);
  InputStream in = response.getEntity().getContent();

  // Do whatever you want with the server response
  // available in "in" InputStream

  ...
}

Note that you'll need to add a whole bunch of error-handling because many of those methods could fail (especially the call to HttpClient.execute), and you'll want to set appropriate timeouts for the calls, otherwise you'll make your HTTP clients want while you contact another service that might tie you up.

If you find that your JSON POST requests are taking a while, you could look into the possibility of putting your work into a separate Thread and using an asynchronous communication model like Websocket to communicate with your clients. You may find that you'll get better overall server performance with a strategy like that.

Upvotes: 3

user5266804
user5266804

Reputation:

For first solution(not reliable):

set the JSON obj in user session, and redirect the user to target cgi/path, the target path would find the JSON object from the session.

//in source servlet
req.getSession().setAttribute("json_obj",json_obj);
req.getSession().setAttribute("another_param",<<anotehr_param>>);
//in the target servlet
JSONObject json=(JSONObject)req.getSession().getAttribute("json_obj");


For second solution:

Set the JSON obj as request attribute and dispatch the request, note some container(some version of tomcat for example) has a bug about encoding with dispatching requests.

//in source servlet
req.setAttribute("json_obj",json_obj);
req.getRequestDispatcher("/target_cgi").forward(req,resp);
//in target servlet
JSONObject json=(JSONObject)req.getAttribute("json_obj");

Upvotes: 1

Related Questions