Blame view

src/main/java/com/huaheng/pc/shipment/kuaidiHeader/service/KuaidiSendService.java 10.5 KB
周鸿 authored
1
2
3
package com.huaheng.pc.shipment.kuaidiHeader.service;
4
import com.huaheng.pc.config.KDCertification.domain.KDCertification;
周鸿 authored
5
6
import org.springframework.stereotype.Service;
周鸿 authored
7
import javax.net.ssl.*;
周鸿 authored
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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.util.Map;
import java.util.TreeMap;


/**
 * 【请填写功能名称】 服务层实现
22
 *
周鸿 authored
23
24
25
26
27
28
 * @author huaheng
 * @date 2022-09-07
 */
@Service
public class KuaidiSendService {
周鸿 authored
29
周鸿 authored
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    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();
        }
    }
周鸿 authored
48
49
50
51

    /**
     * 导入订单
     *
周鸿 authored
52
53
     * @param kdCertification 身份凭证
     * @param orderData       订单信息
周鸿 authored
54
55
     * @return
     */
周鸿 authored
56
57
    public String send(KDCertification kdCertification, String orderData) throws Exception {
        if (null == kdCertification.getAccessToken() || kdCertification.getAccessToken().length() < 1
周鸿 authored
58
59
60
61
62
                || null == orderData || orderData.length() < 1) {
            throw new RuntimeException("无效参数");
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        Map<String, String> data = new TreeMap<>();
周鸿 authored
63
64
        data.put("appid", kdCertification.getAppKey());
        data.put("access_token", kdCertification.getAccessToken());
周鸿 authored
65
66
        data.put("data", orderData);
        data.put("timestamp", timestamp);
周鸿 authored
67
68
69
70
71
        data.put("sign", generateSignByClass(data, kdCertification.getAppSecret()));
        System.out.println("kuaidi-send-data==" + data);
        String result = httpsRequest("https://b.kuaidi100.com/v6/open/api/send", data);
        System.out.println("kuaidi-send==" + result);
        return result;
周鸿 authored
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    }

    /**
     * 生成签名
     *
     * @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());
    }
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    /**
     * 生成签名
     *
     * @param data 请求数据
     * @return 签名
     */
    private static String generateSignByClass(Map<String, String> data, String appSecrets) {
        data = transformToTreeMap(data);
        StringBuilder sbd = new StringBuilder(appSecrets);
        for (Map.Entry<String, String> entry : data.entrySet()) {
            sbd.append(entry.getKey()).append(entry.getValue());
        }
        sbd.append(appSecrets);
        return new MD5().encode(sbd.toString());
    }
106
107
    public static void main(String[] args) {
        Map<String, String> data = new TreeMap<>();
周鸿 authored
108
        data.put("app_key", appKey);
109
        data.put("access_token", "769d68d137bb4fbfa5644c4129cd7c6b");
周鸿 authored
110
111

        data.put("timestamp", "1670460476");
112
        data.put("sign", generateSign(data));
周鸿 authored
113
        data.put("data", "CO202212020000579311");
114
        String str = generateSign(data);
115
116
117
        System.out.println(str);
    }
周鸿 authored
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    /**
     * 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);
    }


    /**
     * 快速打印
     *
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
     * @param kdCertification 身份凭证
     * @param printList       订单号列表
     * @return 打印订单的地址
     */
    public String quickPrintByClass(KDCertification kdCertification, String printList) {
        if (null == kdCertification.getAccessToken() || kdCertification.getAccessToken().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", kdCertification.getAppKey());
        data.put("access_token", kdCertification.getAccessToken());
        data.put("printlist", printList);
        data.put("timestamp", timestamp);
147
        String sign = generateSignByClass(data, kdCertification.getAppSecret());
148
149
150
151
152
153
154
155
        String result = "https://b.kuaidi100.com/v6/open/api/print?appid=" + kdCertification.getAppKey() + "&access_token=" + kdCertification.getAccessToken() + "&printlist=" + printList + "&timestamp=" + timestamp + "&sign=" + sign;
        System.out.println("kuaidi==" + result);
        return result;
    }

    /**
     * 快速打印
     *
周鸿 authored
156
157
158
159
     * @param accessToken 身份凭证
     * @param printList   订单号列表
     * @return 打印订单的地址
     */
160
    public String quickPrint(String accessToken, String printList) {
周鸿 authored
161
162
163
164
165
166
167
168
169
170
171
        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);
172
173
        String result = "https://b.kuaidi100.com/v6/open/api/print?appid=" + appKey + "&access_token=" + accessToken + "&printlist=" + printList + "&timestamp=" + timestamp + "&sign=" + sign;
        System.out.println("kuaidi==" + result);
周鸿 authored
174
        return result;
周鸿 authored
175
    }
周鸿 authored
176
周鸿 authored
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    /**
     * 发送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) {
        }
277
周鸿 authored
278
279
280
        @Override
        public void checkServerTrusted(X509Certificate[] ax509certificate, String s) {
        }
281
周鸿 authored
282
283
284
285
286
287
288
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    }
}