HttpServletRequest JSON 参数在 Servlet 中发现空值

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


我使用以下代码对我使用 webservice 转租的请求进行 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从 web 服务接收。


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


呼如林
浏览 269回答 2
2回答

慕婉清6462132

WebResource 不将数据作为 url 的一部分发送,因此您不能使用request.getParameter. 使用 post 方法将数据作为请求正文发送。使用阅读器读取数据。       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");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java