Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.anjiplus.open.sdk.client.OpenClient Maven / Gradle / Ivy
package com.anjiplus.open.sdk.client;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.anjiplus.open.sdk.utils.SignUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.UnknownHttpStatusCodeException;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* 开放平台客户端
*
* @author lr
*/
public class OpenClient {
/**
* 请求客户端,跳过Ssl验证
*/
private static RestTemplate restTemplate;
/**
* 客户端工厂
*/
private static OpenSkipSslVerificationHttpRequestFactory factory;
private final static String FAILURE_CODE = "500";
public final static String OPEN_ERROR_CODE = "code";
public final static String OPEN_ERROR_MSG = "msg";
/**
* 开放平台地址
*/
private String url;
/**
* 应用私钥
*/
private String secret;
/**
* 应用appId,在开放平台要先创建
*/
private String appId;
/**
* 连接超时
*/
private int connectTimeout;
/**
* 读取超时
*/
private int readTimeout;
/**
* 成功响应标识
*/
String successCode;
/**
* 成功响应标识对应的值
*/
String successValue;
/**
* 请求对应的接口标识
*/
private String method;
/**
* 单个文件参数名
*/
String fileParamName;
/**
* 上传文件
*/
File file;
/**
* 一次上传多个文件
*/
List files;
/**
* 请求头
*/
private Map headers;
/**
* 路径请求参数
*/
private Map params;
/**
* 请求体
*/
Object requestBody;
/**
* 成功回调
*/
Consumer success;
/**
* 失败回调
*/
Consumer fail;
/**
* 解决中文乱码问题
*/
static {
factory = new OpenSkipSslVerificationHttpRequestFactory();
restTemplate = new RestTemplate(factory);
List> messageConverters = restTemplate.getMessageConverters();
for(HttpMessageConverter messageConverter : messageConverters) {
if(messageConverter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) messageConverter).setDefaultCharset(StandardCharsets.UTF_8);
}
}
}
/**
* 构造器
* @param builder
*/
OpenClient(OpenClientBuilder builder) {
this.secret = builder.secret;
this.url = builder.url;
this.appId = builder.appId;
this.connectTimeout = builder.connectTimeout;
this.readTimeout = builder.readTimeout;
this.successCode = builder.successCode;
this.successValue = builder.successValue;
this.method = builder.method;
this.headers = builder.headers;
this.fileParamName = builder.fileParamName;
this.file = builder.file;
this.files = builder.files;
this.params = builder.params;
this.requestBody = builder.requestBody;
this.success = builder.success;
this.fail = builder.fail;
//设置超时时间,默认10秒
factory.setConnectTimeout(connectTimeout);
factory.setReadTimeout(readTimeout);
}
/**
* 开放平台客户端GET调用
*
* @return 请求结果
*/
public JSONObject doGet() {
return doExchange(HttpMethod.GET);
}
/**
* 开放平台客户端GET调用
*
* @return 请求结果
*/
public JSONObject doDelete() {
return doExchange(HttpMethod.DELETE);
}
/**
* 开放平台客户端GET/DELETE调用
*
* @return 请求结果
*/
private JSONObject doExchange(HttpMethod method) {
//判断必填参数
JSONObject errorResult;
if ((errorResult = processBeforeRequest()) != null) {
fail.accept(errorResult);
return errorResult;
}
//Get请求不支持文件上传
if (file != null || files != null) {
errorResult = new JSONObject();
errorResult.put(FAILURE_CODE, "GET请求不支持文件上传,请选择POST请求");
fail.accept(errorResult);
return errorResult;
}
//发送请求
MultiValueMap requestHeaders = new LinkedMultiValueMap();
if (headers != null) {
requestHeaders.setAll(headers);
}
HttpEntity httpEntity = new HttpEntity(requestHeaders);
Map requestParams = getRequestParams();
JSONObject result = new JSONObject();
String uri = getUri(requestParams);
String responseBody = "";
try {
ResponseEntity exchange = restTemplate.exchange(uri, method
, httpEntity, String.class, requestParams);
responseBody = exchange.getBody();
if (responseBody == null) {
result.put(OPEN_ERROR_CODE, FAILURE_CODE);
result.put(OPEN_ERROR_MSG, "返回结果为null");
} else {
result = JSONObject.parseObject(responseBody);
}
} catch (JSONException e) {
result.put(OPEN_ERROR_CODE, FAILURE_CODE);
result.put(OPEN_ERROR_MSG, "返回结果非法JSON格式,结果为:" + responseBody);
} catch (HttpClientErrorException e) {
result.put(OPEN_ERROR_CODE, e.getStatusCode());
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (HttpServerErrorException e) {
result.put(OPEN_ERROR_CODE, e.getStatusCode());
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (UnknownHttpStatusCodeException e) {
result.put(OPEN_ERROR_CODE, HttpStatus.resolve(e.getRawStatusCode()));
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (Exception e) {
result.put(OPEN_ERROR_CODE, HttpStatus.INTERNAL_SERVER_ERROR);
result.put(OPEN_ERROR_MSG, e.getMessage());
}
//响应结果处理
return handleResult(result);
}
/**
* 开放平台客户端POST表单调用
*
* @return 请求结果
*/
public JSONObject doFormPost() {
JSONObject result = new JSONObject();
//发送请求
String uri = "";
String responseBody = "";
try {
//判断必填参数
JSONObject errorResult = null;
if ((errorResult = processBeforeRequest()) != null) {
fail.accept(errorResult);
return errorResult;
}
//请求体封装
MultiValueMap requestBodyMap = new LinkedMultiValueMap<>();
//请求头
HttpHeaders httpHeaders = new HttpHeaders();
//处理单个文件上传
if (file != null) {
httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
if (fileParamName == null) {
fileParamName = "file";
}
FileSystemResource fileSystemResource = new FileSystemResource(file);
requestBodyMap.add(fileParamName, fileSystemResource);
}
//处理多个文件上传
if (files != null) {
httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
if (fileParamName == null) {
fileParamName = "files";
}
List fileSystemResources = new ArrayList<>();
for (File fileTemp : files) {
FileSystemResource fileSystemResource = new FileSystemResource(fileTemp);
fileSystemResources.add(fileSystemResource);
}
requestBodyMap.add(fileParamName, fileSystemResources);
}
//如果为空,则添加表单请求头
if (httpHeaders.isEmpty()) {
httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
}
if (headers != null) {
httpHeaders.setAll(headers);
}
//请求体
if (requestBody != null) {
JSONObject jsonRequestBody = JSONObject.parseObject(JSONObject.toJSONString(requestBody));
requestBodyMap.setAll(jsonRequestBody);
}
HttpEntity httpEntity = new HttpEntity<>(requestBodyMap, httpHeaders);
Map requestParams = getRequestParams();
uri = getUri(requestParams);
ResponseEntity exchange = restTemplate.postForEntity(uri, httpEntity,
String.class, requestParams);
responseBody = exchange.getBody();
if (responseBody == null) {
result.put(OPEN_ERROR_CODE, FAILURE_CODE);
result.put(OPEN_ERROR_MSG, "返回结果为null");
} else {
result = JSONObject.parseObject(responseBody);
}
} catch (JSONException e) {
result.put(OPEN_ERROR_CODE, FAILURE_CODE);
result.put(OPEN_ERROR_MSG, "返回结果非法JSON格式,结果为:" + responseBody);
} catch (HttpClientErrorException e) {
result.put(OPEN_ERROR_CODE, e.getStatusCode());
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (HttpServerErrorException e) {
result.put(OPEN_ERROR_CODE, e.getStatusCode());
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (UnknownHttpStatusCodeException e) {
result.put(OPEN_ERROR_CODE, HttpStatus.resolve(e.getRawStatusCode()));
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (Exception e) {
result.put(OPEN_ERROR_CODE, HttpStatus.INTERNAL_SERVER_ERROR);
result.put(OPEN_ERROR_MSG, e.getMessage());
}
//响应结果处理
return handleResult(result);
}
/**
* 开放平台客户端POST
*
* @return 请求结果
*/
public JSONObject doPost() {
return exchange(HttpMethod.POST);
}
/**
* 开放平台客户端POST
*
* @return put返回结果
*/
public JSONObject doPUT() {
return exchange(HttpMethod.PUT);
}
/**
* 开放平台客户端POST
*
* @return
*/
private JSONObject exchange(HttpMethod method) {
//发送请求
String uri = "";
String responseBody = "";
JSONObject result = new JSONObject();
try {
//判断必填参数
JSONObject errorResult = null;
if ((errorResult = processBeforeRequest()) != null) {
fail.accept(errorResult);
return errorResult;
}
//请求头
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null) {
if (headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
headers.remove(HttpHeaders.CONTENT_TYPE);
}
httpHeaders.setAll(headers);
}
httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
//请求体封装
JSONObject requestBodyMap = new JSONObject();
//请求体
if (requestBody != null) {
JSONObject jsonRequestBody = JSONObject.parseObject(JSONObject.toJSONString(requestBody));
requestBodyMap.putAll(jsonRequestBody);
}
HttpEntity httpEntity = new HttpEntity<>(requestBodyMap.toJSONString(), httpHeaders);
Map requestParams = getRequestParams();
uri = getUri(requestParams);
ResponseEntity exchange = restTemplate.exchange(uri, method, httpEntity, String.class, requestParams);
responseBody = exchange.getBody();
if (responseBody == null) {
result.put(OPEN_ERROR_CODE, FAILURE_CODE);
result.put(OPEN_ERROR_MSG, "返回结果为null");
} else {
result = JSONObject.parseObject(responseBody);
}
} catch (JSONException e) {
result.put(OPEN_ERROR_CODE, FAILURE_CODE);
result.put(OPEN_ERROR_MSG, "返回结果非法JSON格式,结果为:" + responseBody);
} catch (HttpClientErrorException e) {
result.put(OPEN_ERROR_CODE, e.getStatusCode());
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (HttpServerErrorException e) {
result.put(OPEN_ERROR_CODE, e.getStatusCode());
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (UnknownHttpStatusCodeException e) {
result.put(OPEN_ERROR_CODE, HttpStatus.resolve(e.getRawStatusCode()));
result.put(OPEN_ERROR_MSG, e.getMessage());
} catch (Exception e) {
result.put(OPEN_ERROR_CODE, HttpStatus.INTERNAL_SERVER_ERROR);
result.put(OPEN_ERROR_MSG, e.getMessage());
}
//响应结果处理
return handleResult(result);
}
/**
* 请求前拦截
*
* @return 请求前拦截
*/
public JSONObject processBeforeRequest() {
JSONObject jsonObject = new JSONObject();
if (StringUtils.isBlank(url)) {
jsonObject.put(FAILURE_CODE, "开放平台地址为空或不合法");
return jsonObject;
}
if (StringUtils.isBlank(appId)) {
jsonObject.put(FAILURE_CODE, "缺少必填参数:应用appId");
return jsonObject;
}
if (StringUtils.isBlank(method)) {
jsonObject.put(FAILURE_CODE, "缺少必填参数:调用接口名method");
return jsonObject;
}
if (StringUtils.isBlank(secret)) {
jsonObject.put(FAILURE_CODE, "缺少必填参数:应用在开放平台的私钥");
return jsonObject;
}
return null;
}
/**
* 处理返回结果
*
* @param result 请求结果
* @return 响应结果
*/
private JSONObject handleResult(JSONObject result) {
if (result != null && StringUtils.equals(FAILURE_CODE,result.getString(OPEN_ERROR_CODE))) {
if (fail != null) {
fail.accept(result);
}
return result;
}
//成功收到开放平台响应
if (StringUtils.isNotBlank(successCode) && StringUtils.isNotBlank(successValue)) {
//不等于
if (!StringUtils.equals(result.getJSONObject("content").getString(successCode), successValue)) {
fail.accept(result);
return result;
}
}
if (success != null) {
success.accept(result);
}
return result;
}
/**
* 获取请求参数
*
* @return 构造的请求参数
*/
public Map getRequestParams() {
long timestamp = System.currentTimeMillis();
Map requestParams = new HashMap(128);
requestParams.put("appId", appId);
requestParams.put("method", method);
requestParams.put("timestamp", timestamp);
if (params != null) {
requestParams.putAll(params);
}
requestParams.put("sign", getSign(requestParams));
return requestParams;
}
/**
* 拼接正确地url地址
*
* @param requestParams 请求参数
* @return 获取参数拼装的url
*/
public String getUri(Map requestParams) {
StringBuilder stringBuilder = new StringBuilder(url).append("?");
for (String key : requestParams.keySet()) {
stringBuilder.append(key).append("=").append("{").append(key).append("}").append("&");
}
String requestUrl = stringBuilder.toString();
requestUrl = requestUrl.substring(0, requestUrl.length() - 1);
return requestUrl;
}
/**
* 获取请求秘钥
*
* @param requestParams 请求参数(放在路径上的)
* @return 请求秘钥
*/
private String getSign(Map requestParams) {
String sign = SignUtils.generateSign(requestParams, secret);
return sign;
}
}