简体   繁体   中英

HttpServletRequest JSON parameter found null value in Servlet

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?

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"));

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM