为了账号安全,请及时绑定邮箱和手机立即绑定

HttpServletRequest JSON 参数在 Servlet 中发现空值

HttpServletRequest JSON 参数在 Servlet 中发现空值

呼如林 2022-11-30 13:29:40
我正在使用 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 代码。 @Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    String commandid= request.getParameter("commandid");            System.out.println(commandid);       }命令null从 web 服务接收。在webservice中如何获取servlet中的数据?
查看完整描述

2 回答

?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

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


查看完整回答
反对 回复 2022-11-30
?
千万里不及你

TA贡献1784条经验 获得超9个赞

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

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

转换为 JSON:

JSONObject jsonObject = new JSONObject(json);

并获取值:

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


查看完整回答
反对 回复 2022-11-30
  • 2 回答
  • 0 关注
  • 268 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号