大家好,我是雄雄,欢迎关注微信公众号雄雄的小课堂
今天介绍一个案例,糊涂工具类(hutool)post请求设置body参数为json数据,刚开始写的总是报错,下面是正确的代码:
/*** 添加动作* @param projectVo* @return*/@Overridepublic String addProjectV3(@RequestBody ProjectVoV3 projectVo) {JSONObject jsonObjectResult = new JSONObject();//请求接口地址String url = TrainingSchemeConstant.addProjectV3;try {String body = HttpUtil.createPost(url).contentType("application/json").body(JSON.toJSONString(projectVo)).execute().body();if (StringUtils.isBlank(body)) {jsonObjectResult.putOpt("code", "500");jsonObjectResult.putOpt("data", null);jsonObjectResult.putOpt("msg", "操作失败");return jsonObjectResult.toString();}JSONObject obj = JSONUtil.parseObj(body);if (obj == null) {jsonObjectResult.putOpt("code", "500");jsonObjectResult.putOpt("data", null);jsonObjectResult.putOpt("msg", "操作失败");return jsonObjectResult.toString();}String code = obj.get("code").toString();if ("200".equals(code)) {jsonObjectResult.putOpt("code", "200");jsonObjectResult.putOpt("data", obj.get("data"));jsonObjectResult.putOpt("msg", "操作成功");//标记有没有记录//jsonObjectResult.putOpt("count", obj.getJSONArray("data").size());return jsonObjectResult.toString();}} catch (Exception e) {log.error("获取训练方案失败:", e);e.printStackTrace();}return null;}
重点是下面的这行代码:
String body = HttpUtil.createPost(url).contentType("application/json").body(JSON.toJSONString(projectVo)).execute().body();```