如何解决java.lang.NumberFormatException: 调用端口 curl 时为 null
我有以下课程:
@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 -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 示例时,我收到此行 java.lang.NumberFormatException: null
的错误 user_id = Integer.valueOf(request.getParameter("user_id"));
。我想这意味着字符串 user_id
是空的,不能转换为整数。
有什么帮助吗?
解决方法
您正在尝试解析空值。如果您想解析请求的正文,有一种简单的方法可以做到这一点。在您的 xcpd 方法广告中,使用 @RequestBody 注释的参数将自动转换为 java 对象。 getParameter 不是从请求正文中获取字段的正确方法。 请参阅:https://www.baeldung.com/spring-request-response-body
,我认为您应该使用 jsonData
对象来访问 user_id
。
getParameter 方法见文档部分:
对于 HTTP servlet,参数包含在查询字符串或发布的表单数据中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。