public class CreditClient {
private static final Logger logger = LoggerFactory.getLogger(CreditClient.class);
public OkHttpClient okHttpClient;
public static final long DEFAULT_READ_TIMEOUT = 30*1000;
public static final long DEFAULT_WRITE_TIMEOUT = 30*1000;
public static final long DEFAULT_CONNECT_TIMEOUT = 5*1000;
private String apiKey;
private String basePath;
private String secret;
private CreditClient(String apiKey,String secret,String basePath,Long readTimeout,Long writeTimeout,Long connectTimeout) {
this.apiKey = apiKey;
this.basePath = basePath;
this.secret = secret;
okHttpClient = new OkHttpClient
.Builder()
.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.build();
}
private CreditClient(String apiKey,String secret,String basePath) {
this(apiKey,secret,basePath, DEFAULT_READ_TIMEOUT,DEFAULT_WRITE_TIMEOUT,DEFAULT_CONNECT_TIMEOUT);
}
private String executeRaw(String httpMethod, String url, RequestBody requestBody,
Map queryMap,
Map headerMap) throws Exception {
url = url + createOrderedUrlParamFromMap(queryMap);
//组装Headers
Headers.Builder headerBuilder = new Headers.Builder();
if (headerMap != null && !headerMap.isEmpty()) {
headerMap.forEach((k, v) -> headerBuilder.add(k, v));
}
//组装Request
Request request
= new Request.Builder()
.url(url)
.method(httpMethod, requestBody)
.headers(headerBuilder.build())
.build();
//发送请求
Call call = okHttpClient.newCall(request);
Response response = call.execute();
//校验返回
if (!response.isSuccessful()) {
//解析错误信息
String repsStr = response.body().string();
logger.warn(repsStr);
ResponseVo responseVo = JsonUtils.toObj(repsStr, ResponseVo.class);
if (responseVo == null || responseVo.getCode() == null) {
throw new RuntimeException(
"HttpClient调用失败"
+ ", httpStatus=" + response.code()
+ ", URL=" + response.request().url()
+ ", 错误信息:" + repsStr);
} else {
throw new RuntimeException("HttpClient调用失败"
+ ", URL=" + response.request().url()
+ ",错误信息:" + responseVo.toString());
}
}
String body = response.body().string();
return body;
}
public ResponseVo execute(String uri,
String httpMethod,
RequestBody requestBody,
Map paraMap,
Map headMap) throws Exception {
if (null == paraMap) {
paraMap = Maps.newHashMap();
}
if (null == headMap) {
headMap = Maps.newHashMap();
}
long timestamp = System.currentTimeMillis()/1000;
headMap = new ImmutableMap.Builder().putAll(headMap).put(Const.API_HEAD_KEY, apiKey)
.put(Const.API_HEAD_TIMESTAMP, timestamp + "")
.put(Const.API_HEAD_SIGN,
Utils.calSign(apiKey, secret, timestamp,
uri, ImmutableMap.copyOf(paraMap)))
.build();
String body = executeRaw(httpMethod, basePath + uri, requestBody, paraMap, headMap);
ResponseVo responseVo = JsonUtils.toObj(body, ResponseVo.class);
return responseVo;
}