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.X509TrustManager; 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 = "wKa32LXi8F9t"; private static String appSecret = "918dc02a3348480380f607da0bb75c2b"; /** * 导入订单 * * @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; } } }