java.lang.NumberFormatException:调用端口curl调用时为空



我有以下类:

@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是空的,不能转换为整数。

请帮忙好吗?

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

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

参见getParameter方法的文档部分:

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

最新更新