話不多說,直接上代碼!
/** * * <p>Title: QiMenUtils</p> * 奇門加密工具類 * @author huangsq * @date 2018年11月4日 */ public class QiMenUtils { public static void main(String[] args) throws UnsupportedEncodingException { String host = "qimenapi.tbsandbox.com:80/router/qimen/service"; //String host = "gw.api.tbsandbox.com/router/rest"; String appkey = "1025167800"; //String appkey = "testerp_appkey"; String secret = "sandbox2b05dad04e4e68e676cbb9bf0"; String method = "taobao.qimen.returnorder.confirm"; //String method = "taobao.times.get"; //String method = "taobao.qimen.transferorder.report"; String customerId = "c1540886273807"; //String customerId = "stub-cust-code"; //String body = ""; String file = "f:/qimen2.txt"; String body = getFileString(file); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timestamp = "2018-11-08 08:08:08"; StringBuffer url = new StringBuffer(); StringBuffer url1 = new StringBuffer(); url.append("http://"+host+ "?method="+method+ "×tamp="+timestamp+ "&format=xml"+ "&app_key="+appkey+ "&v=2.0"+ "&sign_method=md5"+ "&customerId="+customerId); QiMenUtils qiMenUtils = new QiMenUtils(); String signs = qiMenUtils.sign(url.toString(), body, secret); url1.append("http://"+host+ "?method="+method+ "×tamp="+URLEncoder.encode( timestamp,"utf-8")+ "&format=xml"+ "&app_key="+appkey+ "&v=2.0"+ "&sign_method=md5"+ "&sign="+signs+ "&customerId="+customerId ); String[] urls1 = url1.toString().split("\\?"); System.out.println("?" + urls1[1]); String result = ""; BufferedReader in = null; PrintWriter out = null; try { URL realUrl = new URL(url1.toString()); // 打開和URL之間的連接 URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type","application/xml; charset=utf-8"); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(body); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } System.out.println("result="+result); } public String sign(String url, String body, String secretKey) { Map<String, String> params = getParamsFromUrl(url); // 1. 第一步,確保參數已經排序 String[] keys = params.keySet().toArray(new String[0]); Arrays.sort(keys); // 2. 第二步,把所有參數名和參數值拼接在一起(包含body體) String joinedParams = joinRequestParams(params, body, secretKey, keys); //your_secretKeyapp_keyyour_appkeycustomerIdyour_customerIdformatxmlmethodyour_methodsign_methodmd5timestamp2015-04-26 00:00:07vyour_versionyour_bodyyour_secretKey System.out.println(joinedParams); // 3. 第三步,使用加密算法進行加密(目前僅支持md5算法) String signMethod = params.get("sign_method"); if (!"md5".equalsIgnoreCase(signMethod)) { return null; } byte[] abstractMesaage = digest(joinedParams); // 4. 把二進制轉換成大寫的十六進制 String sign = byte2Hex(abstractMesaage); return sign; } private Map<String, String> getParamsFromUrl(String url) { Map<String, String> requestParams = new HashMap<String, String>(); try { String fullUrl = URLDecoder.decode(url, "UTF-8"); String[] urls = fullUrl.split("\\?"); if (urls.length == 2) { String[] paramArray = urls[1].split("&"); for (String param : paramArray) { String[] params = param.split("="); if (params.length == 2) { requestParams.put(params[0], params[1]); } } } } catch (UnsupportedEncodingException e) { } return requestParams; } private String byte2Hex(byte[] bytes) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int j = bytes.length; char str[] = new char[j * 2]; int k = 0; for (byte byte0 : bytes) { str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } private byte[] digest(String message) { try { MessageDigest md5Instance = MessageDigest.getInstance("MD5"); md5Instance.update(message.getBytes("UTF-8")); return md5Instance.digest(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } private String joinRequestParams(Map<String, String> params, String body, String secretKey, String[] sortedKes) { StringBuilder sb = new StringBuilder(secretKey); // 前面加上secretKey for (String key : sortedKes) { if ("sign".equals(key)) { continue; // 簽名時不計算sign本身 } else { String value = params.get(key); if (isNotEmpty(key) && isNotEmpty(value)) { sb.append(key).append(value); } } } sb.append(body); // 拼接body體 sb.append(secretKey); // 最后加上secretKey return sb.toString(); } private boolean isNotEmpty(String s) { return null != s && !"".equals(s); } public static String getFileString(final String path){ File msgFile = new File(path); StringBuilder txtAll = new StringBuilder(); try{ if(msgFile.isFile() && msgFile.exists()){ InputStreamReader reader = new InputStreamReader(new FileInputStream(msgFile),"UTF-8"); BufferedReader breader = new BufferedReader(reader); String txtValue = ""; while((txtValue = breader.readLine()) != null){ txtAll.append(txtValue); } reader.close(); } }catch(Exception e){ e.printStackTrace(); } return txtAll.toString(); } }