/
OpenApiSDK.java
189 lines (160 loc) · 5.31 KB
/
OpenApiSDK.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/*
Copyright (c) REBUILD <https://getrebuild.com/> and/or its owners. All rights reserved.
rebuild is dual-licensed under commercial and open source licenses (GPLv3).
See LICENSE and COMMERCIAL in the project root for license information.
*/
package com.rebuild.api.sdk;
import cn.devezhao.commons.EncryptUtils;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
/**
* OpenAPI SDK for Rebuild. 建议单例使用
*
* @author ZHAO
* @since 2019-07-23
*/
public class OpenApiSDK {
private static final MediaType JSON_TYPE = MediaType.get("application/json; charset=utf-8");
private static final JSON ERROR_REQ = JSON.parseObject("{ error_code:600, error_msg:'Http request failed' }");
private static final Logger LOG = LoggerFactory.getLogger(OpenApiSDK.class);
final private String appId;
final private String appSecret;
final private String baseUrl;
final private OkHttpClient okHttpClient;
/**
* @param appId
* @param appSecret
*/
public OpenApiSDK(String appId, String appSecret) {
this(appId, appSecret, "https://nightly.getrebuild.com/gw/api/");
}
/**
* @param appId
* @param appSecret
* @param baseUrl
*/
public OpenApiSDK(String appId, String appSecret, String baseUrl) {
this.appId = appId;
this.appSecret = appSecret;
this.baseUrl = baseUrl;
this.okHttpClient = new OkHttpClient().newBuilder()
.retryOnConnectionFailure(false)
.callTimeout(15, TimeUnit.SECONDS)
.build();
}
/**
* @param params
* @return
*/
public String sign(Map<String, Object> params) {
return sign(params, "MD5");
}
/**
* @param reqParams
* @param signType
* @return
*/
public String sign(Map<String, Object> reqParams, String signType) {
Map<String, Object> sortMap = new TreeMap<>();
if (reqParams != null && !reqParams.isEmpty()) {
sortMap.putAll(reqParams);
}
sortMap.put("appid", this.appId);
sortMap.put("timestamp", System.currentTimeMillis() / 1000); // in sec
sortMap.put("sign_type", signType);
StringBuilder sign = new StringBuilder();
for (Map.Entry<String, Object> e : sortMap.entrySet()) {
sign.append(e.getKey())
.append('=')
.append(e.getValue())
.append('&');
}
final String signUrl = sign.toString() + "sign=";
// 拼接
sign.append(this.appId)
.append('.')
.append(this.appSecret);
if ("MD5".equals(signType)) {
return signUrl + EncryptUtils.toMD5Hex(sign.toString());
} else if ("SHA1".equals(signType)) {
return signUrl + EncryptUtils.toSHA1Hex(sign.toString());
} else {
throw new IllegalArgumentException("signType=" + signType);
}
}
/**
* @param url
* @return
* @throws IOException
*/
public JSON httpGet(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = okHttpClient.newCall(request).execute()) {
String resp = Objects.requireNonNull(response.body()).string();
return (JSON) JSON.parse(resp);
}
}
/**
* @param url
* @param post
* @return
* @throws IOException
*/
public JSON httpPost(String url, JSON post) throws IOException {
RequestBody body = RequestBody.create(post.toJSONString(), JSON_TYPE);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = okHttpClient.newCall(request).execute()) {
String resp = Objects.requireNonNull(response.body()).string();
return (JSON) JSON.parse(resp);
}
}
/**
* @param apiName
* @param reqParams
* @return
*/
public JSON get(String apiName, Map<String, Object> reqParams) {
final String apiUrl = buildApiUrl(apiName, reqParams);
try {
return httpGet(apiUrl);
} catch (Exception e) {
LOG.error("Api (GET) failed : " + apiUrl, e);
return ERROR_REQ;
}
}
/**
* @param apiName
* @param reqParams
* @param post
* @return
*/
public JSON post(String apiName, Map<String, Object> reqParams, JSON post) {
final String apiUrl = buildApiUrl(apiName, reqParams);
try {
return httpPost(apiUrl, post);
} catch (Exception e) {
LOG.error("Api (POST) failed : " + apiUrl, e);
return ERROR_REQ;
}
}
private String buildApiUrl(String apiName, Map<String, Object> reqParams) {
StringBuilder apiUrl = new StringBuilder(baseUrl);
if (!baseUrl.endsWith("/")) apiUrl.append('/');
if (apiName.startsWith("/")) apiName = apiName.substring(1);
apiUrl.append(apiName);
apiUrl.append('?').append(sign(reqParams));
return apiUrl.toString();
}
}