Former-commit-id: 2a7412d74fbf24c4beeef257169322289805f44e
master
wangbing 5 years ago
parent f74326117f
commit d3f84721bd

@ -352,7 +352,7 @@ public class ApiCallable implements Callable {
} }
{ {
File file = new File(domain, "ApiClient.java"); File file = new File(domain, "ApiClient.java");
freeMarkerManager.outputTemp(file, "/Java_api/ApiClient.ftl", ctx); freeMarkerManager.outputTemp(file, "/Java_api/ApiClient.java", ctx);
} }
{ {
File file = new File(domain, "ApiRequest.java"); File file = new File(domain, "ApiRequest.java");

@ -1,4 +1,5 @@
package ${domain}; package ${domain};
package com.example.module;
import okhttp3.*; import okhttp3.*;
@ -9,270 +10,264 @@ import java.util.concurrent.TimeUnit;
import java.security.PublicKey; import java.security.PublicKey;
public class ApiClient { public class ApiClient {
private static ApiClient ourInstance = null; private static ApiClient ourInstance = null;
public static void init(String serverUrl, String appKey, String appSecret) { public static void init(String serverUrl, String appKey, String appSecret) {
init(serverUrl, appKey, appSecret, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT); init(serverUrl, appKey, appSecret, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT);
} }
public static void init(String serverUrl, String appKey, String appSecret, int connectTimeout, int readTimeout) { public static void init(String serverUrl, String appKey, String appSecret, int connectTimeout, int readTimeout) {
ourInstance = new ApiClient(serverUrl, appKey, appSecret, connectTimeout, readTimeout); ourInstance = new ApiClient(serverUrl, appKey, appSecret, connectTimeout, readTimeout);
} }
public static ApiClient getInstance() { public static ApiClient getInstance() {
if (ourInstance == null) { if (ourInstance == null) {
System.err.print("ApiClient need init"); System.err.print("ApiClient need init");
} }
return ourInstance; return ourInstance;
} }
//基本请求参数KEY //基本请求参数KEY
private static final String P_APP_KEY = "app_key"; private static final String P_APP_KEY = "app_key";
private static final String P_TYPE = "type"; private static final String P_TYPE = "type";
private static final String P_TARGET = "target"; private static final String P_TARGET = "target";
private static final String P_FILE_NAME = "file_name"; private static final String P_FILE_NAME = "file_name";
private static final String P_TIMESTAMP = "timestamp"; private static final String P_TIMESTAMP = "timestamp";
private static final String P_METHOD = "method"; private static final String P_METHOD = "method";
private static final String P_SIGN = "sign"; private static final String P_SIGN = "sign";
private static final String P_TOKEN = "token_id"; private static final String P_TOKEN = "token_id";
private static final String P_ENHANCED = "enhanced"; private static final String P_ENHANCED = "enhanced";
//参数类型 //参数类型
private static final String TYPE_JSON = "json"; private static final String TYPE_JSON = "json";
private static final String TYPE_FILE = "file"; private static final String TYPE_FILE = "file";
//应用码 //应用码
private String appKey; private String appKey;
//应用安全码 //应用安全码
private String appSecret; private String appSecret;
//服务器地址 //服务器地址
private String serverUrl; private String serverUrl;
//公钥 //公钥
private PublicKey publicKey = null; private PublicKey publicKey = null;
private OkHttpClient httpClient = null; private OkHttpClient httpClient = null;
//默认参数 //默认参数
private static final int DEFAULT_CONNECT_TIMEOUT = 3;//秒 private static final int DEFAULT_CONNECT_TIMEOUT = 3;//秒
private static final int DEFAULT_READ_TIMEOUT = 30;//秒 private static final int DEFAULT_READ_TIMEOUT = 30;//秒
//请求配置 //请求配置
private int connectTimeout;//3秒 private int connectTimeout;//3秒
private int readTimeout;//30秒 private int readTimeout;//30秒
private boolean needCheckRequest = true; // 是否在客户端校验请求 private boolean needCheckRequest = true; // 是否在客户端校验请求
private boolean needEnableParser = true; // 是否对响应结果进行解释 private boolean needEnableParser = true; // 是否对响应结果进行解释
private Before before = null; private Before before = null;
private After after = null; private After after = null;
private String token = ""; private String token = "";
private boolean debug = false; private boolean debug = false;
private ApiClient(String serverUrl, String appKey, String appSecret, int connectTimeout, int readTimeout) { private ApiClient(String serverUrl, String appKey, String appSecret, int connectTimeout, int readTimeout) {
this.connectTimeout = connectTimeout; this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout; this.readTimeout = readTimeout;
this.appKey = appKey; this.appKey = appKey;
this.appSecret = appSecret; this.appSecret = appSecret;
this.serverUrl = serverUrl; this.serverUrl = serverUrl;
this.httpClient = new OkHttpClient.Builder() this.httpClient = new OkHttpClient.Builder()
.readTimeout(readTimeout, TimeUnit.SECONDS) .readTimeout(readTimeout, TimeUnit.SECONDS)
.connectTimeout(connectTimeout, TimeUnit.SECONDS) .connectTimeout(connectTimeout, TimeUnit.SECONDS)
.build(); .build();
} }
public void setPublicKey(PublicKey publicKey) { public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey; this.publicKey = publicKey;
} }
public interface Callback<T extends ApiResponse> { public interface Callback<T extends ApiResponse> {
void call(T response); void call(T response);
} }
public interface Before { public interface Before {
void call(ApiRequest request); void call(ApiRequest request);
} }
public interface After { public interface After {
void call(ApiRequest request, ApiResponse response); void call(ApiRequest request, ApiResponse response);
} }
public void setAfter(After after) { public void setAfter(After after) {
this.after = after; this.after = after;
} }
public void setBefore(Before before) { public void setBefore(Before before) {
this.before = before; this.before = before;
}
public <T extends ApiResponse> T execute(ApiRequest<T> request) {
return execute(request, false);
} }
public <T extends ApiResponse> T execute(ApiRequest<T> request, boolean isEnhanced, ProgressRequestBody.ProgressListener listener) { public <T extends ApiResponse> T execute(ApiRequest<T> request, boolean isEnhanced, ProgressRequestBody.ProgressListener listener) {
if (before != null) { if (before != null) {
before.call(request); before.call(request);
} }
// 检查请求参数 // 检查请求参数
T t = MapperUtil.toJava("{}", request.responseClass()); T t = MapperUtil.toJava("{}", request.responseClass());
if (isEnhanced && publicKey == null) { if (isEnhanced && publicKey == null) {
t.addError(ErrorType.BUSINESS_ERROR, "publicKey can not be null."); t.addError(ErrorType.BUSINESS_ERROR, "publicKey can not be null.");
} }
if (t.hasError()) { if (t.hasError()) {
return t; return t;
} }
try { try {
//装载请求参数 //装载请求参数
String currentTime = String.valueOf(System.currentTimeMillis()); String currentTime = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new MultipartBody.Builder() RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart(P_APP_KEY, appKey) .addFormDataPart(P_APP_KEY, appKey)
.addFormDataPart("encryptData", null, ProgressRequestBody.createProgressRequestBody(encode(request, isEnhanced), listener)) .addFormDataPart("isEnhanced", "false")
.addFormDataPart(P_TIMESTAMP, currentTime) .addFormDataPart("encryptData", null, ProgressRequestBody.createProgressRequestBody(encode(request, isEnhanced), listener))
.addFormDataPart(P_SIGN, sign(request, currentTime)) .addFormDataPart(P_TIMESTAMP, currentTime)
.addFormDataPart(P_ENHANCED, String.valueOf(isEnhanced)) .addFormDataPart(P_SIGN, sign(request, currentTime))
.addFormDataPart(P_TOKEN, token) .addFormDataPart(P_ENHANCED, String.valueOf(isEnhanced))
.build(); .addFormDataPart(P_TOKEN, token)
.build();
Request build = new Request.Builder()
.url(serverUrl + request.apiMethod()) Request build = new Request.Builder()
.post(requestBody) .url(serverUrl + request.apiMethod())
.build(); .post(requestBody)
.build();
Response response = httpClient.newCall(build).execute();
String responseJson = decryptResponse(response, isEnhanced); Response response = httpClient.newCall(build).execute();
t = MapperUtil.toJava(responseJson, request.responseClass()); String responseJson = decryptResponse(response, isEnhanced);
t = MapperUtil.toJava(responseJson, request.responseClass());
} catch (ConnectException e) { } catch (ConnectException e) {
t = MapperUtil.toJava("{}", request.responseClass()); t = MapperUtil.toJava("{}", request.responseClass());
t.addError(ErrorType.SYSTEM_ERROR, "网络异常!"); t.addError(ErrorType.SYSTEM_ERROR, "网络异常!");
} catch (SocketTimeoutException e) { } catch (SocketTimeoutException e) {
t = MapperUtil.toJava("{}", request.responseClass()); t = MapperUtil.toJava("{}", request.responseClass());
t.addError(ErrorType.SYSTEM_ERROR, "请求超时!"); t.addError(ErrorType.SYSTEM_ERROR, "请求超时!");
} catch (IOException e) { } catch (IOException e) {
t = MapperUtil.toJava("{}", request.responseClass()); t = MapperUtil.toJava("{}", request.responseClass());
t.addError(ErrorType.SYSTEM_ERROR, "请求异常!"); t.addError(ErrorType.SYSTEM_ERROR, "请求异常!");
} finally { } finally {
if (after != null) { if (after != null) {
after.call(request, t); after.call(request, t);
} }
} }
return t; return t;
} }
public <T extends ApiResponse> void execute(ApiRequest<T> request, Callback callback) { public <T extends ApiResponse> void execute(ApiRequest<T> request, Callback callback) {
execute(request, false, callback); execute(request, false, callback, null);
} }
public <T extends ApiResponse> void execute(final ApiRequest<T> request, final boolean isEnhanced, final Callback callback) { public <T extends ApiResponse> void execute(final ApiRequest<T> request, final boolean isEnhanced, final Callback callback, ProgressRequestBody.ProgressListener listener) {
if (before != null) { if (before != null) {
before.call(request); before.call(request);
} }
// 检查请求参数 // 检查请求参数
T t = MapperUtil.toJava("{}", request.responseClass()); T t = MapperUtil.toJava("{}", request.responseClass());
if (isEnhanced && publicKey == null) { if (isEnhanced && publicKey == null) {
t.addError(ErrorType.BUSINESS_ERROR, "publicKey can not be null."); t.addError(ErrorType.BUSINESS_ERROR, "publicKey can not be null.");
} }
if (t.hasError()) { if (t.hasError()) {
if (after != null) { if (after != null) {
after.call(request, t); after.call(request, t);
} }
if (callback != null) { if (callback != null) {
callback.call(t); callback.call(t);
} }
return; return;
} }
try { try {
//装载请求参数 //装载请求参数
String currentTime = String.valueOf(System.currentTimeMillis()); String currentTime = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new FormBody.Builder() RequestBody requestBody = new FormBody.Builder()
.add(P_APP_KEY, appKey) .add(P_APP_KEY, appKey)
.add(P_METHOD, request.apiMethod()) .add(P_METHOD, request.apiMethod())
.add(P_TYPE, TYPE_JSON) .add(P_TYPE, TYPE_JSON)
.add(P_TARGET, encode(request, isEnhanced)) // .add(P_TARGET, null, ProgressRequestBody.createProgressRequestBody(encode(request, isEnhanced), listener))
.add(P_TIMESTAMP, currentTime) .add(P_TIMESTAMP, currentTime)
.add(P_SIGN, sign(request, currentTime)) .add(P_SIGN, sign(request, currentTime))
.add(P_ENHANCED, String.valueOf(isEnhanced)) .add(P_ENHANCED, String.valueOf(isEnhanced))
.add(P_TOKEN, token) .add(P_TOKEN, token)
.build(); .build();
Request build = new Request.Builder() Request build = new Request.Builder()
.url(serverUrl) .url(serverUrl + request.apiMethod())
.post(requestBody) .post(requestBody)
.build(); .build();
httpClient.newCall(build).enqueue(new okhttp3.Callback() { httpClient.newCall(build).enqueue(new okhttp3.Callback() {
public void onFailure(Call call, IOException e) { public void onFailure(Call call, IOException e) {
e.printStackTrace(); e.printStackTrace();
T t = MapperUtil.toJava("{}", request.responseClass()); T t = MapperUtil.toJava("{}", request.responseClass());
if (e instanceof ConnectException) { if (e instanceof ConnectException) {
t.addError(ErrorType.BUSINESS_ERROR, "网络异常!"); t.addError(ErrorType.BUSINESS_ERROR, "网络异常!");
} else if (e instanceof SocketTimeoutException) { } else if (e instanceof SocketTimeoutException) {
t.addError(ErrorType.BUSINESS_ERROR, "请求超时!"); t.addError(ErrorType.BUSINESS_ERROR, "请求超时!");
} else { } else {
t.addError(ErrorType.BUSINESS_ERROR, "请求异常!"); t.addError(ErrorType.BUSINESS_ERROR, "请求异常!");
} }
if (after != null) { if (after != null) {
after.call(request, t); after.call(request, t);
} }
if (callback != null) { if (callback != null) {
callback.call(t); callback.call(t);
} }
} }
public void onResponse(Call call, Response response) throws IOException { public void onResponse(Call call, Response response) throws IOException {
T t = null; T t = null;
try { try {
String responseJson = decryptResponse(response, isEnhanced); String responseJson = decryptResponse(response, isEnhanced);
t = MapperUtil.toJava(responseJson, request.responseClass()); t = MapperUtil.toJava(responseJson, request.responseClass());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
t = MapperUtil.toJava("{}", request.responseClass()); t = MapperUtil.toJava("{}", request.responseClass());
t.addError(ErrorType.BUSINESS_ERROR, "服务器走了下神!"); t.addError(ErrorType.BUSINESS_ERROR, "服务器走了下神!");
} }
if (after != null) { if (after != null) {
after.call(request, t); after.call(request, t);
} }
if (callback != null) { if (callback != null) {
callback.call(t); callback.call(t);
} }
} }
}); });
} catch (Exception e) { } catch (Exception e) {
T baseResponse = MapperUtil.toJava("{}", request.responseClass()); T baseResponse = MapperUtil.toJava("{}", request.responseClass());
baseResponse.addError(ErrorType.SYSTEM_ERROR, "请求异常!"); baseResponse.addError(ErrorType.SYSTEM_ERROR, "请求异常!");
if (after != null) { if (after != null) {
after.call(request, baseResponse); after.call(request, baseResponse);
} }
if (callback != null) { if (callback != null) {
callback.call(baseResponse); callback.call(baseResponse);
} }
} }
} }
public void fileUpload(FileUploadRequest request, Callback<FileUploadResponse> callback) {
fileUpload(request, callback, null);
}
public void fileUpload(final FileUploadRequest request, final Callback<FileUploadResponse> callback, ProgressRequestBody.ProgressListener listener) { public void fileUpload(final FileUploadRequest request, final Callback<FileUploadResponse> callback, ProgressRequestBody.ProgressListener listener) {
if (before != null) { if (before != null) {
before.call(request); before.call(request);
} }
try { try {
//检查文件是否存在 //检查文件是否存在
if (!request.isExist()) { if (!request.isExist()) {
FileUploadResponse fileUploadResponse = new FileUploadResponse(); FileUploadResponse fileUploadResponse = new FileUploadResponse();
fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件不存在!"); fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件不存在!");
if (after != null) { if (after != null) {
after.call(request, fileUploadResponse); after.call(request, fileUploadResponse);
} }
callback.call(fileUploadResponse); callback.call(fileUploadResponse);
return; return;
} }
//装载请求参数 //装载请求参数
String currentTime = String.valueOf(System.currentTimeMillis()); String currentTime = String.valueOf(System.currentTimeMillis());
MultipartBody.Builder builder = new MultipartBody.Builder() MultipartBody.Builder builder = new MultipartBody.Builder()
.addFormDataPart(P_APP_KEY, appKey) .addFormDataPart(P_APP_KEY, appKey)
.addFormDataPart(P_METHOD, request.apiMethod()) .addFormDataPart(P_METHOD, request.apiMethod())
.addFormDataPart(P_TYPE, TYPE_FILE) .addFormDataPart(P_TYPE, TYPE_FILE)
@ -280,158 +275,158 @@ public class ApiClient {
.addFormDataPart(P_SIGN, sign(request, currentTime)) .addFormDataPart(P_SIGN, sign(request, currentTime))
.addFormDataPart(P_TOKEN, token); .addFormDataPart(P_TOKEN, token);
if (request.getFile() != null) { if (request.getFile() != null) {
builder.addFormDataPart(P_TARGET, request.getFile().getName(), ProgressRequestBody.createProgressRequestBody(MediaType.parse("image/*"), request.getFile(), listener)); builder.addFormDataPart(P_TARGET, request.getFile().getName(), ProgressRequestBody.createProgressRequestBody(MediaType.parse("image/*"), request.getFile(), listener));
builder.addFormDataPart(P_FILE_NAME, request.getFileName()); builder.addFormDataPart(P_FILE_NAME, request.getFileName());
} else { } else {
builder.addFormDataPart(P_TARGET, null, ProgressRequestBody.createProgressRequestBody(Base64Util.encodeToString(request.getBytes()), listener)); builder.addFormDataPart(P_TARGET, null, ProgressRequestBody.createProgressRequestBody(Base64Util.encodeToString(request.getBytes()), listener));
builder.addFormDataPart(P_FILE_NAME, request.getFileName()); builder.addFormDataPart(P_FILE_NAME, request.getFileName());
} }
MultipartBody multipartBody = builder.build(); MultipartBody multipartBody = builder.build();
Request build = new Request.Builder() Request build = new Request.Builder()
.url(serverUrl) .url(serverUrl)
.post(multipartBody) .post(multipartBody)
.build(); .build();
httpClient.newCall(build).enqueue(new okhttp3.Callback() { httpClient.newCall(build).enqueue(new okhttp3.Callback() {
public void onFailure(Call call, IOException e) { public void onFailure(Call call, IOException e) {
e.printStackTrace(); e.printStackTrace();
FileUploadResponse t = MapperUtil.toJava("{}", FileUploadResponse.class); FileUploadResponse t = MapperUtil.toJava("{}", FileUploadResponse.class);
if (e instanceof ConnectException) { if (e instanceof ConnectException) {
t.addError(ErrorType.BUSINESS_ERROR, "网络异常!"); t.addError(ErrorType.BUSINESS_ERROR, "网络异常!");
} else if (e instanceof SocketTimeoutException) { } else if (e instanceof SocketTimeoutException) {
t.addError(ErrorType.BUSINESS_ERROR, "请求超时!"); t.addError(ErrorType.BUSINESS_ERROR, "请求超时!");
} else { } else {
t.addError(ErrorType.BUSINESS_ERROR, "请求异常!"); t.addError(ErrorType.BUSINESS_ERROR, "请求异常!");
} }
if (after != null) { if (after != null) {
after.call(request, t); after.call(request, t);
} }
if (callback != null) { if (callback != null) {
callback.call(t); callback.call(t);
}
} }
}
public void onResponse(Call call, Response response) throws IOException { public void onResponse(Call call, Response response) throws IOException {
FileUploadResponse t = null; FileUploadResponse t = null;
try { try {
String responseJson = decryptResponse(response, false); String responseJson = decryptResponse(response, false);
t = MapperUtil.toJava(responseJson, FileUploadResponse.class); t = MapperUtil.toJava(responseJson, FileUploadResponse.class);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
t = new FileUploadResponse(); t = new FileUploadResponse();
t.addError(ErrorType.BUSINESS_ERROR, "服务器走了下神!"); t.addError(ErrorType.BUSINESS_ERROR, "服务器走了下神!");
} }
if (after != null) { if (after != null) {
after.call(request, t); after.call(request, t);
} }
if (callback != null) { if (callback != null) {
callback.call(t); callback.call(t);
} }
} }
}); });
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* 对请求进行加密编码 * 对请求进行加密编码
* *
* @param request * @param request
* @return * @return
*/ */
private String encode(ApiRequest request, boolean isEnhanced) { private String encode(ApiRequest request, boolean isEnhanced) {
String json = MapperUtil.toJson(request); String json = MapperUtil.toJson(request);
if (isEnhanced) { if (isEnhanced) {
return RSAUtil.encrypt2Base64(json.getBytes()); return RSAUtil.encrypt2Base64(json.getBytes());
} else { } else {
return AESUtil.encrypt2Base64(json.getBytes(), appSecret); return AESUtil.encrypt2Base64(json.getBytes(), appSecret);
} }
} }
/** /**
* 对响应进行解密 * 对响应进行解密
* *
* @param response * @param response
* @return * @return
*/ */
private String decryptResponse(Response response, boolean isEnhanced) throws IOException { private String decryptResponse(Response response, boolean isEnhanced) throws IOException {
String responseString = response.body().string(); String responseString = response.body().string();
String responseJson; String responseJson;
if (isEnhanced) { if (isEnhanced) {
responseJson = RSAUtil.decrypt2String(responseString); responseJson = RSAUtil.decrypt2String(responseString);
} else { } else {
responseJson = AESUtil.decrypt2String(responseString, appSecret); responseJson = AESUtil.decrypt2String(responseString, appSecret);
} }
if (debug) { if (debug) {
System.out.println("加密响应结果:" + responseString); System.out.println("加密响应结果:" + responseString);
System.out.println("响应结果:" + responseJson); System.out.println("响应结果:" + responseJson);
} }
return responseJson; return responseJson;
} }
/** /**
* 对请求进行签名 * 对请求进行签名
* *
* @param request * @param request
* @return * @return
*/ */
private String sign(ApiRequest request, String currentTime) { private String sign(ApiRequest request, String currentTime) {
if (request instanceof FileUploadRequest) {//文件签名、对文件字节生成的信息摘要签名 if (request instanceof FileUploadRequest) {//文件签名、对文件字节生成的信息摘要签名
FileUploadRequest fileUploadRequest = (FileUploadRequest) request; FileUploadRequest fileUploadRequest = (FileUploadRequest) request;
String encode = MD5Util.encode(fileUploadRequest.getFile() != null ? toByteArray(fileUploadRequest.getFile()) : fileUploadRequest.getBytes()); String encode = MD5Util.encode(fileUploadRequest.getFile() != null ? toByteArray(fileUploadRequest.getFile()) : fileUploadRequest.getBytes());
return MD5Util.encode(appSecret + encode + currentTime); return MD5Util.encode(appSecret + encode + currentTime);
} else {//普通参数签名、此处JSON是经过排序生成的JSON字符串,因此验签时也需要排序 } else {//普通参数签名、此处JSON是经过排序生成的JSON字符串,因此验签时也需要排序
String json = MapperUtil.toJson(request); String json = MapperUtil.toJson(request);
return MD5Util.encode(appSecret + json + currentTime); return MD5Util.encode(appSecret + json + currentTime);
} }
} }
public static byte[] toByteArray(File file) { public static byte[] toByteArray(File file) {
File f = file; File f = file;
if (!f.exists()) { if (!f.exists()) {
return null; return null;
} }
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length()); ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null; BufferedInputStream in = null;
try { try {
in = new BufferedInputStream(new FileInputStream(f)); in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024; int buf_size = 1024;
byte[] buffer = new byte[buf_size]; byte[] buffer = new byte[buf_size];
int len = 0; int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) { while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len); bos.write(buffer, 0, len);
} }
return bos.toByteArray(); return bos.toByteArray();
} catch (IOException e) { } catch (IOException e) {
return null; return null;
} finally { } finally {
try { try {
in.close(); in.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public void setTokenId(String token) { public void setTokenId(String token) {
this.token = token; this.token = token;
} }
public boolean isDebug() { public boolean isDebug() {
return debug; return debug;
} }
public void setDebug(boolean debug) { public void setDebug(boolean debug) {
this.debug = debug; this.debug = debug;
} }
} }

@ -0,0 +1,431 @@
package ${domain};
import okhttp3.*;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;
import java.security.PublicKey;
public class ApiClient {
private static ApiClient ourInstance = null;
public static void init(String serverUrl, String appKey, String appSecret) {
init(serverUrl, appKey, appSecret, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT);
}
public static void init(String serverUrl, String appKey, String appSecret, int connectTimeout, int readTimeout) {
ourInstance = new ApiClient(serverUrl, appKey, appSecret, connectTimeout, readTimeout);
}
public static ApiClient getInstance() {
if (ourInstance == null) {
System.err.print("ApiClient need init");
}
return ourInstance;
}
//基本请求参数KEY
private static final String P_APP_KEY = "app_key";
private static final String P_TYPE = "type";
private static final String P_TARGET = "target";
private static final String P_FILE_NAME = "file_name";
private static final String P_TIMESTAMP = "timestamp";
private static final String P_METHOD = "method";
private static final String P_SIGN = "sign";
private static final String P_TOKEN = "token_id";
private static final String P_ENHANCED = "enhanced";
//参数类型
private static final String TYPE_JSON = "json";
private static final String TYPE_FILE = "file";
//应用码
private String appKey;
//应用安全码
private String appSecret;
//服务器地址
private String serverUrl;
//公钥
private PublicKey publicKey = null;
private OkHttpClient httpClient = null;
//默认参数
private static final int DEFAULT_CONNECT_TIMEOUT = 3;//秒
private static final int DEFAULT_READ_TIMEOUT = 30;//秒
//请求配置
private int connectTimeout;//3秒
private int readTimeout;//30秒
private boolean needCheckRequest = true; // 是否在客户端校验请求
private boolean needEnableParser = true; // 是否对响应结果进行解释
private Before before = null;
private After after = null;
private String token = "";
private boolean debug = false;
private ApiClient(String serverUrl, String appKey, String appSecret, int connectTimeout, int readTimeout) {
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
this.appKey = appKey;
this.appSecret = appSecret;
this.serverUrl = serverUrl;
this.httpClient = new OkHttpClient.Builder()
.readTimeout(readTimeout, TimeUnit.SECONDS)
.connectTimeout(connectTimeout, TimeUnit.SECONDS)
.build();
}
public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
public interface Callback<T extends ApiResponse> {
void call(T response);
}
public interface Before {
void call(ApiRequest request);
}
public interface After {
void call(ApiRequest request, ApiResponse response);
}
public void setAfter(After after) {
this.after = after;
}
public void setBefore(Before before) {
this.before = before;
}
public <T extends ApiResponse> T execute(ApiRequest<T> request, boolean isEnhanced, ProgressRequestBody.ProgressListener listener) {
if (before != null) {
before.call(request);
}
// 检查请求参数
T t = MapperUtil.toJava("{}", request.responseClass());
if (isEnhanced && publicKey == null) {
t.addError(ErrorType.BUSINESS_ERROR, "publicKey can not be null.");
}
if (t.hasError()) {
return t;
}
try {
//装载请求参数
String currentTime = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart(P_APP_KEY, appKey)
.addFormDataPart("isEnhanced", "false")
.addFormDataPart("encryptData", null, ProgressRequestBody.createProgressRequestBody(encode(request, isEnhanced), listener))
.addFormDataPart(P_TIMESTAMP, currentTime)
.addFormDataPart(P_SIGN, sign(request, currentTime))
.addFormDataPart(P_ENHANCED, String.valueOf(isEnhanced))
.addFormDataPart(P_TOKEN, token)
.build();
Request build = new Request.Builder()
.url(serverUrl + request.apiMethod())
.post(requestBody)
.build();
Response response = httpClient.newCall(build).execute();
String responseJson = decryptResponse(response, isEnhanced);
t = MapperUtil.toJava(responseJson, request.responseClass());
} catch (ConnectException e) {
t = MapperUtil.toJava("{}", request.responseClass());
t.addError(ErrorType.SYSTEM_ERROR, "网络异常!");
} catch (SocketTimeoutException e) {
t = MapperUtil.toJava("{}", request.responseClass());
t.addError(ErrorType.SYSTEM_ERROR, "请求超时!");
} catch (IOException e) {
t = MapperUtil.toJava("{}", request.responseClass());
t.addError(ErrorType.SYSTEM_ERROR, "请求异常!");
} finally {
if (after != null) {
after.call(request, t);
}
}
return t;
}
public <T extends ApiResponse> void execute(ApiRequest<T> request, Callback callback) {
execute(request, false, callback, null);
}
public <T extends ApiResponse> void execute(final ApiRequest<T> request, final boolean isEnhanced, final Callback callback, ProgressRequestBody.ProgressListener listener) {
if (before != null) {
before.call(request);
}
// 检查请求参数
T t = MapperUtil.toJava("{}", request.responseClass());
if (isEnhanced && publicKey == null) {
t.addError(ErrorType.BUSINESS_ERROR, "publicKey can not be null.");
}
if (t.hasError()) {
if (after != null) {
after.call(request, t);
}
if (callback != null) {
callback.call(t);
}
return;
}
try {
//装载请求参数
String currentTime = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new FormBody.Builder()
.add(P_APP_KEY, appKey)
.add(P_METHOD, request.apiMethod())
.add(P_TYPE, TYPE_JSON)
// .add(P_TARGET, null, ProgressRequestBody.createProgressRequestBody(encode(request, isEnhanced), listener))
.add(P_TIMESTAMP, currentTime)
.add(P_SIGN, sign(request, currentTime))
.add(P_ENHANCED, String.valueOf(isEnhanced))
.add(P_TOKEN, token)
.build();
Request build = new Request.Builder()
.url(serverUrl + request.apiMethod())
.post(requestBody)
.build();
httpClient.newCall(build).enqueue(new okhttp3.Callback() {
public void onFailure(Call call, IOException e) {
e.printStackTrace();
T t = MapperUtil.toJava("{}", request.responseClass());
if (e instanceof ConnectException) {
t.addError(ErrorType.BUSINESS_ERROR, "网络异常!");
} else if (e instanceof SocketTimeoutException) {
t.addError(ErrorType.BUSINESS_ERROR, "请求超时!");
} else {
t.addError(ErrorType.BUSINESS_ERROR, "请求异常!");
}
if (after != null) {
after.call(request, t);
}
if (callback != null) {
callback.call(t);
}
}
public void onResponse(Call call, Response response) throws IOException {
T t = null;
try {
String responseJson = decryptResponse(response, isEnhanced);
t = MapperUtil.toJava(responseJson, request.responseClass());
} catch (Exception e) {
e.printStackTrace();
t = MapperUtil.toJava("{}", request.responseClass());
t.addError(ErrorType.BUSINESS_ERROR, "服务器走了下神!");
}
if (after != null) {
after.call(request, t);
}
if (callback != null) {
callback.call(t);
}
}
});
} catch (Exception e) {
T baseResponse = MapperUtil.toJava("{}", request.responseClass());
baseResponse.addError(ErrorType.SYSTEM_ERROR, "请求异常!");
if (after != null) {
after.call(request, baseResponse);
}
if (callback != null) {
callback.call(baseResponse);
}
}
}
public void fileUpload(final FileUploadRequest request, final Callback<FileUploadResponse> callback, ProgressRequestBody.ProgressListener listener) {
if (before != null) {
before.call(request);
}
try {
//检查文件是否存在
if (!request.isExist()) {
FileUploadResponse fileUploadResponse = new FileUploadResponse();
fileUploadResponse.addError(ErrorType.BUSINESS_ERROR, "文件不存在!");
if (after != null) {
after.call(request, fileUploadResponse);
}
callback.call(fileUploadResponse);
return;
}
//装载请求参数
String currentTime = String.valueOf(System.currentTimeMillis());
MultipartBody.Builder builder = new MultipartBody.Builder()
.addFormDataPart(P_APP_KEY, appKey)
.addFormDataPart(P_METHOD, request.apiMethod())
.addFormDataPart(P_TYPE, TYPE_FILE)
.addFormDataPart(P_TIMESTAMP, currentTime)
.addFormDataPart(P_SIGN, sign(request, currentTime))
.addFormDataPart(P_TOKEN, token);
if (request.getFile() != null) {
builder.addFormDataPart(P_TARGET, request.getFile().getName(), ProgressRequestBody.createProgressRequestBody(MediaType.parse("image/*"), request.getFile(), listener));
builder.addFormDataPart(P_FILE_NAME, request.getFileName());
} else {
builder.addFormDataPart(P_TARGET, null, ProgressRequestBody.createProgressRequestBody(Base64Util.encodeToString(request.getBytes()), listener));
builder.addFormDataPart(P_FILE_NAME, request.getFileName());
}
MultipartBody multipartBody = builder.build();
Request build = new Request.Builder()
.url(serverUrl)
.post(multipartBody)
.build();
httpClient.newCall(build).enqueue(new okhttp3.Callback() {
public void onFailure(Call call, IOException e) {
e.printStackTrace();
FileUploadResponse t = MapperUtil.toJava("{}", FileUploadResponse.class);
if (e instanceof ConnectException) {
t.addError(ErrorType.BUSINESS_ERROR, "网络异常!");
} else if (e instanceof SocketTimeoutException) {
t.addError(ErrorType.BUSINESS_ERROR, "请求超时!");
} else {
t.addError(ErrorType.BUSINESS_ERROR, "请求异常!");
}
if (after != null) {
after.call(request, t);
}
if (callback != null) {
callback.call(t);
}
}
public void onResponse(Call call, Response response) throws IOException {
FileUploadResponse t = null;
try {
String responseJson = decryptResponse(response, false);
t = MapperUtil.toJava(responseJson, FileUploadResponse.class);
} catch (Exception e) {
e.printStackTrace();
t = new FileUploadResponse();
t.addError(ErrorType.BUSINESS_ERROR, "服务器走了下神!");
}
if (after != null) {
after.call(request, t);
}
if (callback != null) {
callback.call(t);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*
* @param request
* @return
*/
private String encode(ApiRequest request, boolean isEnhanced) {
String json = MapperUtil.toJson(request);
if (isEnhanced) {
return RSAUtil.encrypt2Base64(json.getBytes());
} else {
return AESUtil.encrypt2Base64(json.getBytes(), appSecret);
}
}
/**
*
*
* @param response
* @return
*/
private String decryptResponse(Response response, boolean isEnhanced) throws IOException {
String responseString = response.body().string();
String responseJson;
if (isEnhanced) {
responseJson = RSAUtil.decrypt2String(responseString);
} else {
responseJson = AESUtil.decrypt2String(responseString, appSecret);
}
if (debug) {
System.out.println("加密响应结果:" + responseString);
System.out.println("响应结果:" + responseJson);
}
return responseJson;
}
/**
*
*
* @param request
* @return
*/
private String sign(ApiRequest request, String currentTime) {
if (request instanceof FileUploadRequest) {//文件签名、对文件字节生成的信息摘要签名
FileUploadRequest fileUploadRequest = (FileUploadRequest) request;
String encode = MD5Util.encode(fileUploadRequest.getFile() != null ? toByteArray(fileUploadRequest.getFile()) : fileUploadRequest.getBytes());
return MD5Util.encode(appSecret + encode + currentTime);
} else {//普通参数签名、此处JSON是经过排序生成的JSON字符串,因此验签时也需要排序
String json = MapperUtil.toJson(request);
return MD5Util.encode(appSecret + json + currentTime);
}
}
public static byte[] toByteArray(File file) {
File f = file;
if (!f.exists()) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
return null;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void setTokenId(String token) {
this.token = token;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
}

@ -295,17 +295,18 @@ public class GlobalController implements ErrorController {
@RequestParam boolean isEnhanced, @RequestParam boolean isEnhanced,
@RequestParam long timestamp, @RequestParam long timestamp,
@RequestParam String encryptData) { @RequestParam String encryptData) {
BaseResponse response = null; BaseResponse response = new BaseResponse();;
String data = null; String data = null;
String appSecret = "1234567890123456"; String appSecret = "1234567890123456";
// 解码 // 解码
if (isEnhanced) { try {
data = RSAUtil.decrypt2String(encryptData); if (isEnhanced) {
} else { data = RSAUtil.decrypt2String(encryptData);
data = AESUtil.decrypt2String(encryptData, appSecret); } else {
} data = AESUtil.decrypt2String(encryptData, appSecret);
if (data == null) { }
response.addError(ErrorType.BUSINESS_ERROR, "解码失败,请确认编码是否正确!"); }catch (Exception e){
response.addError(ErrorType.BUSINESS_ERROR,"解码失败,请确认编码是否正确!");
} }
// 验证签名 // 验证签名

@ -138,7 +138,7 @@ public class ActionConfig implements BeanDefinitionRegistryPostProcessor {
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) { public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
String beanClassName = beanDefinition.getBeanClassName(); String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null && beanClassName.endsWith("Api")) { if (beanClassName != null && beanClassName.endsWith("Api")) {
beanClassName = beanClassName.substring(0, beanClassName.length() - 4); beanClassName = beanClassName.substring(0, beanClassName.length() - 3);
} }
String beamName = beanClassName.replaceAll(basePackage + ".", API_PREFIX).replaceAll("\\.","/").toLowerCase(); String beamName = beanClassName.replaceAll(basePackage + ".", API_PREFIX).replaceAll("\\.","/").toLowerCase();
LogUtil.i("registry api " + beamName); LogUtil.i("registry api " + beamName);

Loading…
Cancel
Save

Powered by TurnKey Linux.