【问题标题】:java.lang.NumberFormatException: null when calling a port curl calljava.lang.NumberFormatException:调用端口 curl 调用时为 null
【发布时间】:2021-02-09 11:10:17
【问题描述】:

我有以下课程:

    @CrossOrigin()
    @PostMapping(path = "/xcpd", produces = "application/json; charset=utf-8")
    protected String xcpd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        JSONObject jsonData = null;
        JSONObject jObj = new JSONObject();
        JSONObject responseXCPD = null;
        int user_id = -1;
        int pid = -1;
        try {
            if ((jsonData = new JSONObject(getJSONString(request))) != null) {
                if (jsonData.has("country_code") && jsonData.has("identifier")) {
                    
                    // User data
                    user_id = Integer.valueOf(request.getParameter("user_id"));
                    String rolename = String.valueOf(request.getParameter("rolename"));
                    ....
                   }
                }
         }
}

我正在使用以下 curl 调用来调用此端点:

curl -X POST -H "Content-Type: application/json" http://localhost:8083/xcpd -d '{"user_id":"1", 
      "country_code":"IE",
      "rolename": "doctor",
      "identifier": "1.1.1.1"
}' 

当我调用 curl 示例时,我收到此行 user_id = Integer.valueOf(request.getParameter("user_id")); 的错误 java.lang.NumberFormatException: null。我想这意味着字符串user_id 是空的,不能转换成整数。

有什么帮助吗?

【问题讨论】:

    标签: java curl http-post spring-tool-suite


    【解决方案1】:

    您正在尝试解析空值。如果您想解析请求的正文,有一种简单的方法可以做到这一点。在您的 xcpd 方法广告中,使用 @RequestBody 注释的参数将自动转换为 java 对象。 getParameter 不是从请求正文中获取字段的正确方法。 见:https://www.baeldung.com/spring-request-response-body

    【讨论】:

      【解决方案2】:

      我认为您应该使用您的jsonData 对象来访问user_id

      getParameter 方法见文档部分:

      对于 HTTP servlet,参数包含在查询字符串或发布的表单数据中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-19
        • 2017-01-04
        相关资源
        最近更新 更多