0

I'm using Servlet to handle request and response.

I have used following code to Servlet my request to sublet using webservice:

 JSONObject parans = new JSONObject();
    parans.put("commandid", "Enamu7l");
    System.out.println("parans = " + parans);        
    Client restClient = Client.create();
    WebResource webResource = restClient.resource("URL");
    ClientResponse resp = webResource.accept(MediaType.APPLICATION_JSON)
            .post(ClientResponse.class, parans.toJSONString());

Here is my servlet code to receive data.

 @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String commandid= request.getParameter("commandid");        
    System.out.println(commandid);       
}

commandid recieve null from webservice.

What to do in webservice to get data in servlet?

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Enamul Haque
  • 4,789
  • 1
  • 37
  • 50

2 Answers2

1

WebResource not sending the data as part of the url, so you can not use request.getParameter. The data is send as request body using the post method.Read the data using the reader.

       StringBuilder sb = new StringBuilder();
        while ((s = request.getReader().readLine()) != null) {
            sb.append(s);
        }
       JSONObject jSONObject = new JSONObject(sb.toString());

        System.out.println(jSONObject.getString("commandid"));
star67
  • 1,505
  • 7
  • 16
Srinivasan Sekar
  • 2,049
  • 13
  • 22
0

You are sending JSON in request body, so you need to get it:

String json = request.getReader().lines().collect(Collectors.joining());

Convert to JSON:

JSONObject jsonObject = new JSONObject(json);

And get the value:

String value = jsonObject.getString("commandid");
Ori Marko
  • 56,308
  • 23
  • 131
  • 233