跳至主要內容

如何对接第三方系统

Mr.XuJava必知必会约 803 字大约 3 分钟

1. 一般对接流程

  • 查阅文档,找到满足要求的接口,根据文档,用postman测试,是否能够访问
  • 访问鉴权接口,获取token
  • 封装请求参数,请求对接接口
  • 解析响应体
  • 根据需求处理对接结果

telnet ip port

推送的形式

主动的访问第三方接口

2. 代码编写,建议层级

定时任务层---->业务层---->访问接口层

  • 定时层代码示例

    @Component
    public class CollectHuaWeiBigDataJob {
    
        @Autowired
        private IHuaweiYunAccessBigDataService huaweiYunAccessBigDataService;
    
        @XxlJob("collectHuaWeiCloudBigDataTenantJob")
        public ReturnT<String> collectEcsInstance651DataJob(String param) {
    
            long start = System.currentTimeMillis();
            XxlJobLogger.log("XXL-JOB, collectHuaWeiCloudBigDataTenantJob beginning");
            huaweiYunAccessBigDataService.collectBigDataTenantInfo();
            XxlJobLogger.log("XXL-JOB, collectHuaWeiCloudBigDataTenantJob ending");
            return ReturnT.SUCCESS;
        }
    }
    
  • 业务层代码示例

     @Service
    public class HuaweiYunAccessBigDataServiceImpl implements IHuaweiYunAccessBigDataService {
    
        @Autowired
        private HuaWeiBigDataHttpUtils huaWeiBigDataHttpUtils;
    
        @Override
        @Transactional
        public void collectBigDataTenantInfo() {
            String datas = huaWeiBigDataHttpUtils.getBigDataInfo("url");
            //处理结果
            if (datas != null && !"".equals(datas)) {
                // BigDataTenantResp bigDataTenantResp = JSONObject.parseObject(datas, BigDataTenantResp.class);
                List<BigDataTenantResp> bigDataTenantResps = JSONObject.parseArray(datas, BigDataTenantResp.class);
                if (CollectionUtils.isNotEmpty(bigDataTenantResps)) {
                    bigDataTenantResps.forEach(bigDataTenantResp -> {
                        //获取集群id
                        Integer clusterId = bigDataTenantResp.getClusterId();
                        //获取租户信息
                        List<BigDataTenantResp.Tenant> tenants = bigDataTenantResp.getTenants();
                        if (CollectionUtils.isNotEmpty(tenants)) {
                            List<BigDataTenantDto> dtos = tenants.stream().map(e -> {
                                BigDataTenantDto bigDataTenantDto = new BigDataTenantDto();
                                bigDataTenantDto.setClusterId(clusterId).setParentId(e.getParentId())
                                        .setTenantId(e.getId()).setTenantName(e.getName()).setUpdateTime(new Date());
                                return bigDataTenantDto;
                            }).collect(Collectors.toList());
    
                               //入库操作
                               //1、直接删除,再插入
                               /* bigDataTenantMapper.deleteAll();
                                //新增
                                bigDataTenantMapper.insertBatch(dtos);*/
                            //2、比对数据库数据,区分出需要删除的数据、需要更新的数据、需要新增的数据,分别进行对应操作
                             //判断出查询的设备信息,哪些需要更新的,哪些需要删除的,哪些需要新增的,分别进行操作
                                    /*List<String> equipKeysOld = dceEquipInfoMapper.queryAllEquipKey();
                                    List<String> equipKeysNew = dtoList.stream().map(DceEquipInfoDto::getEquipKey).collect(Collectors.toList());
                                    //查询出需要删除的数据
                                    equipKeysOld.forEach(key -> {
                                        if (!equipKeysNew.contains(key)) {
                                            deleteList.add(key);
                                        }
                                    });
                                    //查询出需要新增或者更新的数据
                                    dtoList.forEach(e -> {
                                        if (!equipKeysOld.contains(e.getEquipKey())) {
                                            addList.add(e.setCreateTime(new Date()).setUpdateTime(new Date()));
                                        } else {
                                            updateList.add(e.setUpdateTime(new Date()));
                                        }
                                    });*/
                        }
    
                    });
                }
            }
        }
    }
    
    
  • 访问接口层代码示例

@Component
@Slf4j
public class HuaWeiBigDataHttpUtils {


    private RestTemplate restTemplate;

    @PostConstruct
    public void init() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

        //配置信赖策略
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        // 配置NoopHostnameVerifier.INSTANCE (new NoopHostnameVerifier() 也行)
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        requestFactory.setConnectTimeout(50000);
        requestFactory.setReadTimeout(50000);
        restTemplate = new RestTemplate(requestFactory);
    }

    public String  getBigDataInfo(String url) {
        try {
             //restTemplate默认进行了url编码,使用URI.create(url)可以不使用restTemplate的url编码
            //如果url中的参数已经进行了url编码,则要用下面这个代码进行请求
            //%3AB67878AB%
            //ResponseEntity<String> responseEntity = restTemplate.exchange(URI.create(url), HttpMethod.GET, getBigDataHttpEntity(), String.class);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, getBigDataHttpEntity(), String.class);
            if (responseEntity.getStatusCode().equals(HttpStatus.OK) && !responseEntity.getBody().contains("</script>")) {
                String body = responseEntity.getBody();
                return body;
            } else {
                log.warn("Huawei cloud 811 big data  fetch  fail,url=====" + url + ", response code: ", responseEntity.getStatusCode());
            }
        } catch (Exception e) {
            log.error("Huawei cloud  811 big data  fetch  error,url=====" + url, e);
        }
        return null;
    }


    public HttpEntity<Object> getBigDataHttpEntity() throws UnsupportedEncodingException {
        HttpHeaders httpHeaders = new HttpHeaders();
        String encoding = DatatypeConverter.printBase64Binary(("username" + ":" + "password").getBytes("UTF-8"));
        httpHeaders.set("Authorization", "Basic " + encoding);
        httpHeaders.set("Accept", "application/json");
        httpHeaders.set("Content-Type", "application/json");
        HttpEntity<Object> httpEntity = new HttpEntity<>(httpHeaders);
        return httpEntity;
    }

xml转换成json

public class XMLUtils {


    /**
    * @Description: xml转json
    * @Date: 2023/7/11  10:34
    * @Param xmlStr:
    * @return: com.alibaba.fastjson.JSONObject
    **/
    public static JSONObject xml2Json(String xmlStr) throws DocumentException {
        Document doc = DocumentHelper.parseText(xmlStr);
        JSONObject json = new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    public static void dom4j2Json(Element element, JSONObject json) {
        List<Element> chdEl = element.elements();
        for(Element e : chdEl){
            if (!e.elements().isEmpty()) {
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
            } else {
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }
}

3.在xxljob的管理界面配置任务