【问题标题】:HttpServletRequest JSON parameter found null value in ServletHttpServletRequest JSON 参数在 Servlet 中发现空值
【发布时间】:2019-10-02 14:20:47
【问题描述】:

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

我已使用以下代码来 Servlet 使用 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());

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

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

commandid 从 web 服务接收 null

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

【问题讨论】:

标签: java json rest servlets


【解决方案1】:

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

【讨论】:

【解决方案2】:

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

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

转换为 JSON:

JSONObject jsonObject = new JSONObject(json);

并获取值:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    相关资源
    最近更新 更多