com.anjiplus.open.sdk.client.OpenClient Maven / Gradle / Ivy
package com.anjiplus.open.sdk.client;
import com.alibaba.fastjson.JSONObject;
import com.anjiplus.open.sdk.utils.SignUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
/**
* 开放平台客户端
*
* @author lr
*/
public class OpenClient {
/**
* 请求客户端
*/
private RestTemplate restTemplate = new RestTemplate();
private final static String SUCCESS_CODE = "200";
private final static String FAILURE_CODE = "500";
private final static String RESPONSE_CODE = "code";
/**
* 开放平台地址
*/
private String url;
/**
* 应用私钥
*/
private String secret;
/**
* 应用appId,在开放平台要先创建
*/
private String appId;
/**
* 请求对应的接口标识
*/
private String method;
/**
* 请求头
*/
private Map headers;
/**
* 路径请求参数
*/
private Map pathParams;
/**
* 请求体
*/
Object requestBody;
/**
* 成功回调
*/
Consumer success;
/**
* 失败回调
*/
Consumer fail;
/**
* 构造器
* @param builder
*/
OpenClient(OpenClientBuilder builder) {
this.secret = builder.secret;
this.url = builder.url;
this.appId = builder.appId;
this.method = builder.method;
this.headers = builder.headers;
this.pathParams = builder.pathParams;
this.requestBody = builder.requestBody;
this.success = builder.success;
this.fail = builder.fail;
}
/**
* 开放平台客户端GET调用
* @return 请求结果
*/
public JSONObject doGet() {
//判断必填参数
JSONObject errorResult = null;
if((errorResult = processBeforeRequest()) != null) {
fail.accept(errorResult);
return errorResult;
};
//发送请求
MultiValueMap multiValueMap = new LinkedMultiValueMap();
if(headers != null) {
multiValueMap.setAll(headers);
}
HttpEntity httpEntity = new HttpEntity(multiValueMap);
Map requestParams = getRequestParams();
ResponseEntity exchange = restTemplate.exchange(getUrl(requestParams), HttpMethod.GET
, httpEntity, JSONObject.class, requestParams);
//响应结果处理
return handleResult(exchange);
}
/**
* 开放平台客户端POST调用
* @return 请求结果
*/
public JSONObject doPost() {
//判断必填参数
JSONObject errorResult = null;
if((errorResult = processBeforeRequest()) != null) {
fail.accept(errorResult);
return errorResult;
};
//请求头
HttpHeaders httpHeaders = new HttpHeaders();
if(headers != null) {
httpHeaders.setAll(headers);
}
HttpEntity