手机淘宝api签名(sign)的算法(Java版)
1、自己创建一个utils包,并创建一个类,命名为TaoBao,如下图:

2、在TaoBao这个类里粘贴如下代码:public static String getSign(String url, String secret) throws Exception { String[] urls = url.split("&"); return Signing(urls, secret); } private static String Signing(String[] urls, String secret) throws Exception { Map<String, String> params = new HashMap<String, String>(); for (int i = 0; i < urls.length; i++) { String item[] = urls[i].split("="); params.put(item[0], item[1]); } // 第一步:检查参数是否已经排序 String[] keys = params.keySet().toArray(new String[0]); Arrays.sort(keys); // 第二步:把所有参数名和参数值串在一起 StringBuilder strBuilder = new StringBuilder(); for (String key : keys) { String value = params.get(key); strBuilder.append(key).append(value); } // 第三步:使用MD5/HMAC加密 byte[] bytes = encryptHMAC(strBuilder.toString(), secret); // 第四步:把二进制转化为大写的十六进制 return byte2hex(bytes); } private static byte[] encryptHMAC(String data, String secret) throws IOException { byte[] bytes = null; try { SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacMD5"); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); bytes = mac.doFinal(data.getBytes("UTF-8")); } catch (GeneralSecurityException gse) { Log.e("TB_ERR", gse.getMessage()); } return bytes; } public static String byte2hex(byte[] bytes) { StringBuilder sign = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() == 1) { sign.append("0"); } sign.append(hex.toUpperCase()); } return sign.toString(); }

4、到此步骤已经基本完成api的签名算法了,想要查看运行效果,右击项目,run as -> android application即可在手机端查看效果,如下图
