OkHttp完美封装,用一行代码搞定外部请求,使用起来很方便( 二 )

在 Springboot 中使用maven引入
<dependency><groupId>io.github.admin4j</groupId><artifactId>common-http-starter</artifactId><version>0.4.0</version></dependency>最新版查询 io.github.admin4j:common-http-starter
spring 版可以对 OkHttp进行个性化配置
配置详见
public class HttpConfig {/*** 日志等级*/private HttpLoggingInterceptor.Level loggLevel = HttpLoggingInterceptor.Level.BODY;/*** 读取超时时间 , 秒*/private long readTimeout = 30;/*** 链接超时时间*/private long connectTimeout = 30;private boolean followRedirects = false;/*** 最大的连接数*/private int maxIdleConnections = 5;/*** 最大的kepAlive 时间 秒*/private long keepAliveDuration = 5;private String userAgent = "OKHTTP";/*** 是否支持cookie*/private boolean cookie = false;private ProxyConfig proxy;@Datapublic static class ProxyConfig {private Proxy.Type type = Proxy.Type.HTTP;private String host;private Integer port = 80;private String userName;private String password;}}如何快速封装外部接口以实体项目为例 , 封装 ebay接口
public class EbayClient extends ApiJsonClient {/*** 店铺配置** @param storeId*/public EbayClient(Long storeId) {//TODO 获取店铺相关配置Map<String, String> config = new HashMap<>();basePath = "https://api.ebay.com";defaultHeaderMap.put("Authorization", "Bearer " + config.get("accessToken"));defaultHeaderMap.put("X-EBAY-C-MARKETPLACE-ID", config.get("marketplaceId"));}}EbayClient 封装ebay api请求 基础类
/** * ebay 库存相关api * @author andanyang */public class EbayInventoryClient extends EbayClient {/*** 店铺配置** @param storeId*/public EbayInventoryClient(Long storeId) {super(storeId);}/*** 库存列表** @param limit* @param offset* @return* @throws IOException*/public JSONObject inventoryItem(Integer limit, Integer offset) throws IOException {Map<String, Object> queryMap = new HashMap(2);queryMap.put("limit", limit);queryMap.put("offset", offset);return get("/sell/inventory/v1/inventory_item", queryMap);}}EbayInventoryClient 封装ebay 库存 api请求
使用
EbayInventoryClient ebayInventoryClient=new EbayInventoryClient(1L);JSONObject jsonObject=ebayInventoryClient.inventoryItem(0,10);/** * 订单相关api * @author andanyang */public class EbayOrderClient extends EbayClient {/*** 店铺配置** @param storeId*/public EbayOrderClient(Long storeId) {super(storeId);}/*** 订单列表** @param beginTime* @param endTime* @param limit* @param offset* @return*/public JSONObject orders(String beginTime, String endTime, int limit, int offset) {final String path = "/sell/fulfillment/v1/order";String filter = MessageFormat.format("lastmodifieddate:[{0}..{1}]", beginTime, endTime);//Map<String, Object> queryMap = new HashMap<>(8);queryMap.put("filter", filter);queryMap.put("limit", limit);queryMap.put("offset", offset);return get("/sell/inventory/v1/inventory_item", queryMap);}}库存相关的使用EbayInventoryClient , 订单相关的使用EbayOrderClient , 是不是很清晰
源码位置:

https://github.com/admin4j/common-http


推荐阅读