Java方法通过RestTemplate调用restful接口

时间:2022-04-03 00:38:19

背景:项目A需要在代码内部调用项目B的一个restful接口,该接口是POST方式,header中 Authorization为自定义内容,主要传输的内容封装在body中,所以使用到了RestTemplate。

    public String batchInsertData(ImportEntity importEntity, String token) {

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(MEDIATYPE_JSON_UTF8);
        headers.setContentType(type);
        headers.set("Authorization", token);

        HttpEntity<ImportEntity> entity = new HttpEntity<>(importEntity, headers);
        try {
            ResponseEntity<Object> result = restTemplate.exchange(httpsHost + IMPORT_HOSPITALDEPT_DATA, HttpMethod.POST, entity, Object.class);
            if (null != result && result.getStatusCode() == HttpStatus.OK) {
                if (result.getBody() != null) {
                    LinkedHashMap<String, String> hashMap = (LinkedHashMap<String, String>) result.getBody();
                    return hashMap.getOrDefault("msg", "导入成功!");
                } else {
                    return StringUtils.EMPTY;
                }
            }
        } catch (Exception e) {
            LOGGER.error("导入失败!", e);
            return "导入失败!";
        }
        return "导入成功!";
    }

调用 get 请求:

    private boolean validMessageCode(String validateCode, String phone, String type, boolean invalidWhenVerify) {
        LOG.info("cUserUrl : " + cUserUrl + "; validateCode: " + validateCode +  "; phone: " + phone);
        StringBuilder url = new StringBuilder();
        url.append(cUserUrl).append(VERIFY_MSGCODE)
                .append(StringPool.QUESTION_MARK)
                .append("msgCode").append(StringPool.EQUAL_SIGN).append(validateCode).append(StringPool.AND)
                .append("phone").append(StringPool.EQUAL_SIGN).append(phone).append(StringPool.AND)
                .append("invalidWhenVerify").append(StringPool.EQUAL_SIGN).append(invalidWhenVerify).append(StringPool.AND)
                .append("type").append(StringPool.EQUAL_SIGN).append(type);
        String response = restTemplate.exchange(url.toString(), HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), String.class).getBody();
        LOG.info("response : " + response);
        JSONObject jsonObject = JSON.parseObject(response);
        if (StringPool.ZERO != jsonObject.get(StringPool.RET_CODE)) {
            return false;
        }
        return true;
    }