亲宝软件园·资讯

展开

Java调用第三方接口封装实现

wangfenglei123456 人气:0

介绍

在Java项目中,会遇到很多调用第三方接口的地方,比如接入微信,其他公司的系统,需要传token或者签名。由于接入调用接口很多,每个接口内部都需要手动设置token或者其他数据,这就显得很麻烦。而且发送http请求还需要自己创建request对象。下面介绍2中封装方式,

一、利用feign功能封装请求,所有接口和服务之间调用是一样的,只需要执行后面的url,参数类,请求方式等。内部需要传输的token信息,在自定的拦截器中设置,自定义的拦截器需要实现RequestInterceptor接口。在这里面设置公共的请求参数。比较推荐的。

二、自己封装一个通用的请求类,里面自己创建Request对象,发送完http请求之后拿到返回的json对象在封装返回类,借助于ObjectMapper类。

一、借助feign实现调用

写一个feign的接口调用类,因为调用服务和接收服务不在一个注册中心,所以需要指定url,并实现拦截器

自定义的feign接口

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
 
@FeignClient(
    url = "${e-sign.apiHost}",        // 这个值在配置文件中配置好
    value = "authFeign"               // 这个是自定义的服务名称,没有用
)
@RequestMapping(
    headers = {"X-Tsign-Open-Auth-Mode=Signature"}    // 设置请求的header
)
public interface EAuthFeign {
    
// 写封装的参数和请求路径
    @PostMapping({"/v3/oauth2/index"})
    EResponse<String> applyAuth(@RequestBody EApplyAuthDTO params);
}

配置文件内容

e-sign:
  projectId: 111111
  projectSecret: fasdfads
  apiHost: https://ss.sign.cn
  callbackHost: https://call.baidu.com
  redirectHost: https://web.baidu.com

自定义拦截器,这个是feign的拦截器,只需要标记被扫描到就行,会自动加载。写了这个类后,这个类所在的项目所有的feign都会被这个拦截器控制

import common.exception.E;
import esign.config.ESignConfig;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
 
@Component
public class EAuthFeignRequestInterceptor implements RequestInterceptor {
    private static final Logger log = LoggerFactory.getLogger(EAuthFeignRequestInterceptor.class);
    @Autowired
    private ESignConfig eSignConfig;
    private static final BASE64Encoder encodeBase64 = new BASE64Encoder();
 
    public EAuthFeignRequestInterceptor() {
    }
 
    public void apply(RequestTemplate template) {
        String host = this.eSignConfig.getApiHost();
        String url = template.url();
        String target = template.feignTarget().url();
        boolean b = target.equals(host);
// 这个判断就是为了防止所有的feign都走这个拦截器,限制只有第三方接口才能进入下面的逻辑
        if (b) {
            template.header("X-Tsign-Open-App-Id", new String[]{this.eSignConfig.getProjectId()});
            Map<String, Collection<String>> headers = template.headers();
            Collection<String> authMode = (Collection)headers.get("X-Tsign-Open-Auth-Mode");
            boolean isSign = authMode != null && authMode.contains("Signature");
            if (isSign) {
                template.header("X-Tsign-Open-Ca-Timestamp", new String[]{String.valueOf(System.currentTimeMillis())});
                template.header("Accept", new String[]{"*/*"});
                template.header("Content-Type", new String[]{"application/json;charset=UTF-8"});
 
                try {
                    this.setMd5AndSignature(template);
                } catch (Exception var10) {
                    log.error("发送请求失败, url:{}, params:{}", url, new String(template.body()));
                    throw new E("发送请求失败");
                }
            } else {
                template.header("X-Tsign-Open-Authorization-Version", new String[]{"v2"});
            }
 
            log.info("发送请求, url:{}, params:{}", url, template.body() == null ? "" : new String(template.body()));
        }
    }
 
    public void setMd5AndSignature(RequestTemplate template) {
        byte[] body = template.body();
        String url = template.url();
        String method = template.method();
        String contentMD5 = doContentMD5(body);
        if ("GET".equals(method) || "DELETE".equals(method)) {
            contentMD5 = "";
            url = URLDecoder.decode(url);
        }
 
        String message = appendSignDataString(method, "*/*", contentMD5, "application/json;charset=UTF-8", "", "", url);
        log.info("接口,url:{}, 签名字符串:{}", url, message);
        String reqSignature = doSignatureBase64(message, this.eSignConfig.getProjectSecret());
        template.header("Content-MD5", new String[]{contentMD5});
        template.header("X-Tsign-Open-Ca-Signature", new String[]{reqSignature});
    }
 
    private static String doContentMD5(byte[] body) {
        if (body == null) {
            return "";
        } else {
            byte[] md5Bytes = null;
            MessageDigest md5 = null;
            String contentMD5 = null;
 
            try {
                md5 = MessageDigest.getInstance("MD5");
                md5.update(body);
                byte[] md5Bytes = md5.digest();
                contentMD5 = encodeBase64.encode(md5Bytes);
                return contentMD5;
            } catch (NoSuchAlgorithmException var5) {
                log.error("不支持此算法", var5);
                throw new E("不支持此算法");
            }
        }
    }
 
    private static String doSignatureBase64(String message, String secret) {
        String algorithm = "HmacSHA256";
        String digestBase64 = null;
 
        try {
            Mac hmacSha256 = Mac.getInstance(algorithm);
            byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
            byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
            hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, algorithm));
            byte[] digestBytes = hmacSha256.doFinal(messageBytes);
            digestBase64 = encodeBase64.encode(digestBytes);
            return digestBase64;
        } catch (NoSuchAlgorithmException var8) {
            log.error("不支持此算法", var8);
            throw new E("不支持此算法");
        } catch (InvalidKeyException var9) {
            log.error("无效的密钥规范", var9);
            throw new E("无效的密钥规范");
        }
    }
 
    private static String appendSignDataString(String method, String accept, String contentMD5, String contentType, String date, String headers, String url) {
        StringBuilder sb = new StringBuilder();
        sb.append(method).append("\n").append(accept).append("\n").append(contentMD5).append("\n").append(contentType).append("\n").append(date).append("\n");
        if ("".equals(headers)) {
            sb.append(headers).append(url);
        } else {
            sb.append(headers).append("\n").append(url);
        }
 
        return new String(sb);
    }
}

配置类

@Configuration
@ConfigurationProperties(
    prefix = "e-sign"
)
public class ESignConfig {
    private static final Logger log = LoggerFactory.getLogger(ESignConfig.class);
    private String projectId;
    private String projectSecret;
    private String apiHost;
    private String callbackHost;
    private String redirectHost;
}

上边几个类就可以封装对外请求了。自己服务根据要求可以另外处理

二、自己封装请求类

通用请求返回结果类

package com.service;
 
import com.alibaba.fastjson.JSONObject;
import com.common.dto.coop.HttpDTO;
import com.common.vo.coop.ThirdResultVO;
import com.cooperation.generator.ThirdTokenGenerator;
import com.cooperation.template.TokenTemplate;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
 
/**
 * 基于okhttp的请求客户端的service
 *
 * @author aaa 2022-04-28
 */
@Slf4j
@Service
public class HttpService2 {
 
    @Autowired
    private TokenTemplate tokenTemplate;
 
    /**
     * 获取接口调用返回值
     *
     * @param param 请求参数
     * @author aaa 2022-04-28
     */
    public ThirdResultVO getInterfaceResult(HttpDTO param) {
 
        // 参数转换成json
        JSONObject json = Objects.isNull(param.getObj()) ? new JSONObject()
                : JSONObject.parseObject(JSONObject.toJSONString(param.getObj()));
 
        // 如果需要token,将token放在参数中
        if (param.getNeedToken()) {
 
            String token = tokenTemplate.getToken(new ThirdTokenGenerator());
 
            json.put("token", token);
        }
 
        // 发起请求,获得响应
        Response response = doRequest(param.getUrl(), json);
 
        // 处理返回值
        ThirdResultVO ThirdResult = handleReturn(response);
 
        // 如果为null,响应有问题,不能转成返回值类型
        Assert.notNull(ThirdResult, "接口调用异常");
 
        return ThirdResult;
    }
 
    /**
     * 处理返回值
     *
     * @param response 请求响应
     * @author aaa 2022-04-28
     */
    private ThirdResultVO handleReturn(Response response) {
        // 如果响应为空,返回null
        if (Objects.isNull(response)) {
            return null;
        }
 
        try {
            // 如果响应体为空,返回null
            if (Objects.isNull(response.body())) {
                return null;
            }
 
            // 响应体的字节数组
            byte[] bytes = response.body().bytes();
            log.info("调用接口返回数据--:{}", new String(bytes));
            // 转换成返回值类型
            return JSONObject.parseObject(bytes, ThirdResultVO.class);
 
        } catch (Exception e) {
            log.info("处理返回值失败:{}", e.getMessage(), e);
        }
 
        return null;
    }
 
    /**
     * 发送请求
     *
     * @param url        请求地址
     * @param jsonObject 参数DTO
     * @author aaa 2022-04-28
     */
    private Response doRequest(String url, JSONObject jsonObject) {
 
        // 获得表单请求对象
        Request formRequest = getFormRequest(url, jsonObject);
 
        // 调用接口 请求入参
        log.info("调用接口请求入参--:url:{} , jsonObject :{}",url, JSONObject.toJSONString(jsonObject));
 
        // 获得okhttp请求工具
        OkHttpClient requestClient = getRequestClient();
 
        // 获得请求调用对象
        Call call = requestClient.newCall(formRequest);
 
        // 发起请求,获得响应
        Response execute = null;
        try {
            execute = call.execute();
        } catch (IOException e) {
            log.info("调用接口失败:{}", e.getMessage(), e);
        }
 
        return execute;
    }
 
    /**
     * 获得表单请求
     *
     * @param url        请求地址
     * @param jsonObject 参数DTO
     * @author aaa 2022-04-28
     */
    private Request getFormRequest(String url, JSONObject jsonObject) {
 
        // 获得请求构造器
        Request.Builder requestBuilder = new Request.Builder();
 
        // 设置表单请求的请求头
        try {
            requestBuilder.addHeader("content-type", "application/x-www-form-urlencoded").post(getFormBody(jsonObject)).url(new URL(url));
        } catch (MalformedURLException e) {
            log.info("url转换失败:{}", e.getMessage(), e);
        }
 
        // 返回请求对象
        return requestBuilder.build();
    }
 
    /**
     * 获取请求客户端
     *
     * @author aaa 2022-04-28
     */
    private OkHttpClient getRequestClient() {
        return new OkHttpClient.Builder()
                .readTimeout(2L, TimeUnit.MINUTES)
                .build();
    }
 
    /**
     * 获取form表单请求的body
     *
     * @param jsonObject 请求参数DTO
     * @author aaa 2022-04-28
     */
    private FormBody getFormBody(JSONObject jsonObject) {
 
        // 获取表单请求构造器
        FormBody.Builder fb = new FormBody.Builder();
 
        // 设置请求参数
        jsonObject.keySet().forEach(item -> fb.addEncoded(item, jsonObject.getString(item)));
 
        // 返回body
        return fb.build();
    }
}

通用请求参数类

@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public class HttpDTO implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    @NotNull(message = "请求路径不能为空")
    @NotBlank(message = "请求路径不能为空")
    @ApiModelProperty(value = "请求路径url")
    private String url;
 
    @ApiModelProperty(value = "参数")
    private Object obj;
 
    @NotNull(message = "是否需要token 不能为空")
    @ApiModelProperty(value = "是否需要token:true是,false否")
    private Boolean needToken;
}

请求调用示例

public List<String> getSkuCode(String classifyCode) {
 
        ResultVO interfaceResult = httpService.getInterfaceResult(new HttpDTO()
                .setUrl(Constant.HOST.concat(Constant.GOODS_GET_SKUS_BY_CLASSID_URI))
                .setNeedToken(true)
                .setObj(new DeLiGetSkusByClassId3DTO().setCode(classifyCode3).setIsAll(1)));
 
        log.info(interfaceResult.getResultMessage());
 
        return JSONArray.parseArray(interfaceResult.getResult(), String.class);
    }

上边的请求返回,从结果里取出result字符串,再转一下list,这可以放在后面的请求方法中,传一个返回的类class。使用objectMapper转一下。

private ObjectMapper mapper = new ObjectMapper();
 
public <T, RR> Response<RR> api(ApiDTO<T> jsonParams, Class<RR> responseResult) {
        String json = JSONObject.toJSONString(jsonParams);
        log.info("三方api.do, requestParams:{}", json);
        String responseStr = this.thirdFileAgentFeign.api(json);
        // 构建返回类型
        JavaType javaType1 = this.mapper.getTypeFactory().constructParametricType(YZResponse.class, new Class[]{responseResult});
 
        try {
            // 这个代码块就看这里返回带泛型的类
            return (Response)this.mapper.readValue(responseStr, javaType1);
        } catch (JsonProcessingException e) {
            log.error("反序列化返回值异常, responseStr:{}, errInfo:{}", new Object[]{responseStr, var7.getMessage(), e});
            throw new E("反序列化返回值异常");
        }
    }

第二种返回类型

import com.fasterxml.jackson.core.type.TypeReference;
 
public static <T> T toObj(String json, Class<T> type) {
        try {
            return MAPPER.readValue(json, type);
        } catch (IOException e) {
            log.error("toObj error", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }
 
public static <T> T toObj(String json, TypeReference<T> typeReference) {
        try {
            return mapper.readValue(json, typeReference);
        } catch (IOException e) {
            log.error("toObj error", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

泛型返回处理可以参考RestTemplate里面的postForObject()

Class<?> deserializationView = ((MappingJacksonInputMessage)inputMessage).getDeserializationView();
                if (deserializationView != null) {
                    // 部分代码,构建一个reader
                    ObjectReader objectReader = this.objectMapper.readerWithView(deserializationView).forType(javaType);
                    if (isUnicode) {
                    // 返回class类型的对象
                        return objectReader.readValue(inputMessage.getBody());
                    }
 
                    Reader reader = new InputStreamReader(inputMessage.getBody(), charset);
                    return objectReader.readValue(reader);
                }

具体可以学习一下ObjectMapper的用法

请求接口返回结果类

@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public class ResultVO implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    @ApiModelProperty(value = "接口返回成功与否")
    private Boolean success;
 
    @ApiModelProperty(value = "返回数据描述")
    private String resultMessage;
 
    @ApiModelProperty(value = "平台业务代码标记")
    private String resultCode;
 
// 返回的json结果,再处理成返回对象
    @ApiModelProperty(value = "业务数据")
    private String result;
}

三、调用第三方生成token,可以使用策略类实现

策略接口类

public interface TokenGeneratorStrategy {
    /**
     * 获取token
     *
     * @author aaa 2022-04-26
     */
    String getToken();
 
    /**
     * 获取token缓存key
     *
     * @author aaa 2022-04-26
     */
    String getTokenCacheKey();
 
    /**
     * 获取token过期时间,采用redis单位
     *
     * @author aaa 2022-04-26
     */
    Duration getTokenExpireTime();
 
}

获取token的实现类

package com.generator;
 
import com.alibaba.fastjson.JSONObject;
import com.common.constant.ThirdConstant;
import com.common.constant.MallCacheKeyConstant;
import com.common.constant.MallCommonConstant;
import com.common.dto.coop.HttpDTO;
import com.common.vo.coop.ThirdResultVO;
import com.common.vo.coop.ThirdTokenVO;
import com.cooperation.dto.ThirdTokenDTO;
import com.cooperation.service.HttpService;
import com.cooperation.strategy.TokenGeneratorStrategy;
import com.common.exception.E;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
 
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
 
/**
 * 三方生成token
 *
 */
@Slf4j
@Service
public class ThirdTokenGenerator implements TokenGeneratorStrategy {
 
    @Autowired
    private HttpService httpService;
 
    @Override
    public String getToken() {
 
        // 获取当前时间,转换成yyyy/MM/dd格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = LocalDateTime.now().format(dateTimeFormatter);
 
        // 签名规则:client_secret+timestamp+client_id+username+password+scope+client_secret将上面字符串MD5 加密后转为小写。
        String sign = ThirdConstant.CLIENT_SECRET
                .concat(format)
                .concat(ThirdConstant.CLIENT_ID)
                .concat(ThirdConstant.USERNAME)
                .concat(ThirdConstant.PASSWORD)
                .concat(ThirdConstant.CLIENT_SECRET);
 
        // md5 加密
        String signMd5 = DigestUtils.md5DigestAsHex(sign.getBytes(StandardCharsets.UTF_8)).toLowerCase();
 
        ThirdTokenDTO ThirdTokenDto = new ThirdTokenDTO().setClient_id(ThirdConstant.CLIENT_ID).setClient_secret(ThirdConstant.CLIENT_SECRET)
                .setUsername(ThirdConstant.USERNAME).setPassword(ThirdConstant.PASSWORD)
                .setTimestamp(format).setSign(signMd5);
 
        // 接口调用
        ThirdResultVO interfaceResult = httpService.getInterfaceResult(
                new HttpDTO()
                        .setUrl(ThirdConstant.HOST.concat(ThirdConstant.TOKEN_URI))
                        .setObj(ThirdTokenDto)
                        .setNeedToken(false));
 
 
        ThirdTokenVO ThirdToken = new ThirdTokenVO();
        try {
            ThirdToken = JSONObject.parseObject(interfaceResult.getResult(), ThirdTokenVO.class);
        } catch (Exception e) {
            log.info("token 返回值处理异常:{}", e.getMessage(), e);
        }
        if (Objects.isNull(ThirdToken)) {
            log.error("获取三方token为空----{}", interfaceResult);
            throw new E("获取三方token异常信息--" + interfaceResult.getResultMessage());
        }
 
        return ThirdToken.getAccess_token();
    }
 
    @Override
    public String getTokenCacheKey() {
        return MallCacheKeyConstant.COOP_Third_TOKEN + MallCommonConstant.DEFAULT_KEY;
    }
 
    /**
     * 三方有效时间一小时,这里的过期时间采用50分钟
     */
    @Override
    public Duration getTokenExpireTime() {
 
        // 当前时间到12点的时间
        Duration nowTo12 = Duration.between(LocalDateTime.now(), LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
 
        // 50分钟
        Duration fiftyMin = Duration.ofSeconds(50 * 60L);
 
        // 如果当前时间到12点的时间超过50分钟,返回50分钟
        if (nowTo12.compareTo(fiftyMin) > 0) {
            return fiftyMin;
        }
 
        // 否则返回当前时间到12点的时间
        return nowTo12;
    }
}

总结

加载全部内容

相关教程
猜你喜欢
用户评论