HttpServletRequest JSON 参数在 Servlet 中发现空值

HttpServletRequest JSON parameter found null value in Servlet

我正在使用 Servlet 来处理请求和响应。

我使用以下代码对我使用 web 服务转租的请求进行 Servlet:

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

这是我接收数据的 servlet 代码。

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

命令从网络服务接收 null

在webservice中如何获取servlet中的数据?

WebResource 不作为 url 的一部分发送数据,因此您可以 使用 request.getParameter。数据使用 post method.Read 作为请求正文发送,数据使用 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"));

您在请求正文中发送JSON,因此您需要获取它:

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

转换为JSON:

JSONObject jsonObject = new JSONObject(json);

并获取值:

String value = jsonObject.getString("commandid");