当前位置:网站首页>Hutool post requests to set the body parameter to JSON data

Hutool post requests to set the body parameter to JSON data

2022-07-07 01:40:00 Mu Xiongxiong

Hello everyone , I'm Xiong Xiong , Welcome to WeChat official account. Xiongxiong's small class

Today, I will introduce a case , Muddle headed tool class (hutool)post The request is set body Parameter is json data , What you write at first is always wrong , Here is the correct code :

/** *  Add action  * @param projectVo * @return */
	@Override
	public String addProjectV3(@RequestBody  ProjectVoV3 projectVo) {
    
		JSONObject jsonObjectResult = new JSONObject();
		// Request interface address 
		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", " operation failed ");
				return jsonObjectResult.toString();
			}
			JSONObject obj = JSONUtil.parseObj(body);
			if (obj == null) {
    
				jsonObjectResult.putOpt("code", "500");
				jsonObjectResult.putOpt("data", null);
				jsonObjectResult.putOpt("msg", " operation failed ");
				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", " Successful operation ");
				// Mark whether there is any record 
				//jsonObjectResult.putOpt("count", obj.getJSONArray("data").size());
				return jsonObjectResult.toString();
			}
		} catch (Exception e) {
    
			log.error(" Failed to get training plan :", e);
			e.printStackTrace();
		}
		return null;
	}

The key point is the following line of code :

String body = HttpUtil.createPost(url)
				.contentType("application/json")
				.body(JSON.toJSONString(projectVo)).execute().body();
				```


原网站

版权声明
本文为[Mu Xiongxiong]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061805438713.html