1、封装工具类
@Component @Slf4j public class RestTemplateUtil{ @Value("${cebcs_get_token_url}") private String cbecsTokenUrl; public String getToken() { RestTemplate restTemplate = new RestTemplate(); //获取token ResponseEntity<String> result = restTemplate.getForEntity(cbecsTokenUrl, String.class); if (result != null) { JSONObject map = JSONObject.parseObject(result.getBody()); if ("0".equals(map.get("code"))) { throw new DeptException("获取token失败"); }else { String token = (String) map.get("token"); return token; } }else { throw new DeptException("获取token异常"); } } public void dockingInterface(String token, String body,String url, HttpMethod method) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("x-auth-token", token); httpHeaders.add("Content-Type","application/json"); HttpEntity<String> requestEntity = new HttpEntity<>(body, httpHeaders); ResponseEntity<String> result = restTemplate.exchange(url, method, requestEntity, String.class); if (result != null) { JSONObject map = JSONObject.parseObject(result.getBody()); if (!"0".equals(map.get("code").toString())) { throw new DeptException((String)map.get("message")); } }else { throw new DeptException("系统异常"); } } }
2、使用
String token = getKJToken.getToken(); Map<String, Object> params = new HashMap<>(); String url = cbecsRemoveUserUrl; params.put("id", sysUser.getUserId()); getKJToken.dockingInterface(token, JSONObject.toJSONString(params), url, HttpMethod.DELETE);