KuaidiSendService.java
8.11 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package com.huaheng.pc.shipment.kuaidiHeader.service;
import com.huaheng.pc.config.token.service.ITokensService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
/**
* 【请填写功能名称】 服务层实现
*
* @author huaheng
* @date 2022-09-07
*/
@Service
public class KuaidiSendService {
private static String appKey = "dEalu7vYJMAA"; //昆山华恒焊接股份有限公司
private static String appSecret = "5447e797b54442778d12da773172d397";
static {
try {
SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
public boolean verify(String s, SSLSession sslsession) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 导入订单
*
* @param accessToken 身份凭证
* @param orderData 订单信息
* @return
*/
public String send(String accessToken, String orderData) throws Exception {
if (null == accessToken || accessToken.length() < 1
|| null == orderData || orderData.length() < 1) {
throw new RuntimeException("无效参数");
}
String timestamp = String.valueOf(System.currentTimeMillis());
Map<String, String> data = new TreeMap<>();
data.put("appid", appKey);
data.put("access_token", accessToken);
data.put("data", orderData);
data.put("timestamp", timestamp);
data.put("sign", generateSign(data));
return httpsRequest("https://b.kuaidi100.com/v6/open/api/send", data);
}
/**
* 生成签名
*
* @param data 请求数据
* @return 签名
*/
private static String generateSign(Map<String, String> data) {
data = transformToTreeMap(data);
StringBuilder sbd = new StringBuilder(appSecret);
for (Map.Entry<String, String> entry : data.entrySet()) {
sbd.append(entry.getKey()).append(entry.getValue());
}
sbd.append(appSecret);
return new MD5().encode(sbd.toString());
}
/**
* 把map转换为treeMap
*
* @param map 任意类型的map
* @return treeMap
*/
private static Map<String, String> transformToTreeMap(Map<String, String> map) {
return map instanceof TreeMap ? map : new TreeMap<>(map);
}
/**
* 快速打印
*
* @param accessToken 身份凭证
* @param printList 订单号列表
* @return 打印订单的地址
*/
public String quickPrint(String accessToken, String printList) {
if (null == accessToken || accessToken.length() < 1
|| null == printList || printList.length() < 1) {
throw new RuntimeException("无效参数");
}
String timestamp = String.valueOf(System.currentTimeMillis());
Map<String, String> data = new TreeMap<>();
data.put("appid", appKey);
data.put("access_token", accessToken);
data.put("printlist", printList);
data.put("timestamp", timestamp);
String sign = generateSign(data);
return "https://b.kuaidi100.com/v6/open/api/print?appid=" + appKey + "&access_token=" + accessToken + "&printlist=" + printList + "×tamp=" + timestamp + "&sign=" + sign;
}
/**
* 发送http请求
*
* @param url 请求地址
* @param data 请求参数
* @return 接口返回的结果
*/
private static String httpsRequest(String url, Map<String, String> data) throws Exception {
URL apiUrl = new URL(url);
StringBuilder sbd = new StringBuilder();
StringBuilder paramSbd = new StringBuilder();
if (null != data) {
for (Map.Entry<String, String> entry : data.entrySet()) {
paramSbd.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
}
String param = paramSbd.length() > 0 ? paramSbd.substring(0, paramSbd.length() - 1) : "";
try {
HttpURLConnection httpConn = (HttpURLConnection) apiUrl.openConnection();
//设置参数
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setUseCaches(false);
httpConn.setRequestMethod("POST");
//设置请求属性
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("Accept", "application/json;charset=UTF-8");
//建立输入流,向指向的URL传入参数
OutputStream out = httpConn.getOutputStream();
out.write(param.getBytes("UTF-8"));
out.flush();
out.close();
//获得响应状态
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
String readLine;
BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sbd.append(readLine).append("\n");
}
responseReader.close();
System.out.println(sbd.toString());
} else {
throw new RuntimeException("http请求失败:" + httpConn.getResponseCode());
}
} catch (Exception e) {
throw new RuntimeException("http请求失败", e);
}
return sbd.toString();
}
static class MD5 {
// 获得MD5摘要算法的 MessageDigest 对象
private MessageDigest _mdInst = null;
private char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private MessageDigest getMdInst() {
if (_mdInst == null) {
try {
_mdInst = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return _mdInst;
}
String encode(String s) {
try {
byte[] btInput = s.getBytes("UTF-8");
// 使用指定的字节更新摘要
getMdInst().update(btInput);
// 获得密文
byte[] md = getMdInst().digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
static class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate certificates[], String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] ax509certificate, String s) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
}