RestTemplate調用第三方接口實現數據傳輸

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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章