对接第三方接口教程(发送Http请求及返回参数处理)

发布时间 2023-06-01 11:56:49作者: 了悟

1.首先Http工具类建议使用

 

package cn.hutool.http;
//这个包下面的
HttpUtil.post(String urlString, String body)
这个方法会省去很多事情,不用去设置header的一些基本东西,get就不说了,get也能用post请求,把参数拼url后边就行了

 2.要看第三方接口的鉴权是如何做的,如果是token鉴权,那么在请求业务方法之前还要先请求获取token的接口。获取token后最好把token放到缓存里,避免每次都请求token。

如果是秘钥鉴权,比较简单,把秘钥放在body里,跟参数一块发过去,主要看第三方的接口文档。如果需要秘钥放在header里,那么要用 HttpUtil.createPost()这个方法。

3.是要看返回值的处理,一般先有个状态码,为成功的话处理,否则抛异常

最好写一个映射实体类,和返回的data里的一致,然后强转就可以了。图快的话也可以用map

4.代码案例,下面贴两个代码段

1)

HashMap<String,Object> req = new HashMap<>();
        req.put("product","xx");  //鉴权用
        req.put("sign","xxx-xxx");//签名,相当于秘钥,鉴权用
        req.put("userId",erpUserId);
        HashMap<String,Object> formData = new HashMap<>();
        formData.put("name",crmCustomer.getCustomerName()); 
        formData.put("relaCustsupCode",crmCustomerExt.getCustomerCode());
        formData.put("province",crmCustomerExt.getAddrProvince());
        formData.put("city",crmCustomerExt.getAddrCity());
        formData.put("inPool",crmCustomerExt.getIsEnterpool());
        formData.put("custIndustry",crmCustomerExt.getCustomerIndustry());
        req.put("formData",formData);
        String codeMsg = "";
        try{
            JSONObject o = (JSONObject) JSON.toJSON(req); //先把map转成josn对象
            String body = HttpUtil.post(ERP_DOMAIN_URL+"/api-suppliers/busi/comm/api/ibf/suppliers/bl/add", o.toJSONString()); //把josn对象转成josn字符串
            JSONObject jsonObject = JSON.parseObject(body);
            if (jsonObject != null && jsonObject.get("code").equals("0000")) {
                JSONObject data = (JSONObject) jsonObject.get("data");
                //todo 返回值处理  根据给的接口文档,对返回参数进行处理,也可以debug跟文档对一下return true;
            } else {
                codeMsg = jsonObject.get("codeMsg").toString();
                throw new CrmException(500,codeMsg);
            }
        } catch (Exception e) {
            log.error("推送数据至ERP失败,请重试!客户:" +crmCustomer.getCustomerName());
            throw new CrmException(500,codeMsg);
        }

 

2)

try {
            String body = HttpUtil.createPost("http://url/crm_department_info/execute")
                    .header("Content-Type","application/json;charset=UTF-8")
                    .header("appKey","xx")
                    .header("appSecret","xxxxx")
                    .execute().body();
            JSONObject jsonObject = JSON.parseObject(body); //将返回的信息转成json对象
            if (jsonObject != null && jsonObject.get("code").equals(200)) {
                if (jsonObject.get("data") == null) {
                    return true;
                } else {
                    JSONArray data = (JSONArray) jsonObject.get("data");  //这个data里是一个list。这里有两种处理方案,一种是声明类,字段与JsonArray里的一致,然后强转出来,不想写类的话,就用我下面这种
                    List<HashMap<String,Object>> hashMapList = new ArrayList<>();
                    List<DeptIdCodeMatch> deptIdCodeMatchList = this.queryDeptIdCodeMatchList();
                    Map<String, DeptIdCodeMatch> maps = deptIdCodeMatchList.stream().collect(Collectors.toMap(
                            DeptIdCodeMatch::getDeptCode, Function.identity(), (key1, key2) -> key2));
                    for (Object obj: data) {
                        HashMap<String,Object> hp = JSONObject.parseObject(JSONObject.toJSONString(obj), HashMap.class);//遍历JsonArray,放到map里
                        hashMapList.add(hp);
                    }

                    Set<String> codeSet = new HashSet<>();//对数据去查
                    if (hashMapList != null && !hashMapList.isEmpty()) {
                        hashMapList.forEach(v -> {
                            String parentdeptCode = v.get("parentId").toString();
                            String deptCode = v.get("id").toString();
                            codeSet.add(parentdeptCode);
                            codeSet.add(deptCode);
                        });
                        this.insertDeptCodeList(codeSet);
                    }
                    List<AdminDept> list = new ArrayList<>();
                    hashMapList.forEach(v->{//映射实体类
                        AdminDept adminDept = new AdminDept();
                        adminDept.setParentdept(v.get("parentId").toString());
                        adminDept.setOwnerUserName(v.get("userName").toString());
                        adminDept.setCode(v.get("id").toString());
                        adminDept.setName(v.get("groupName").toString());
                        adminDept.setPid(maps.get(v.get("parentId").toString()).getDeptId());
                        list.add(adminDept);
                    });
                    if (list == null || list.size() == 0) {
                        return true;
                    }
                    this.getBaseMapper().saveOrUpdateAdminDeptSyncErp(list);
                    return true;
                }

            } else {
                log.error("查询数据失败!日期:"+formatDate);
            }
        } catch (Exception e) {
            log.error("同步数据失败!日期:"+formatDate);
        }