Loading
0

java智能外呼机器人签名失败的原因

public static void main(String[] args) throws Exception { String url ="Timestamp=2016-02-23T12%3A46:24Z&Format=XML&AccessKeyId=testid&Action=CreateIntent&SignatureMethod=HMAC-SHA1&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&Version=2019-12-26&SignatureVersion=1.0"; String[] split = url.split("&");

    Map<String, String> map = new HashMap<>();
for (String str : split) {
System.out.println("str:"+str);
String[] splitkeyValue = str.split("=");
map.put(splitkeyValue[0],splitkeyValue[1]);
}
String getStringToSign = getStringToSign(map, "GET");
String sign = getSign(getStringToSign,AccessKeySecret);
System.out.println("sign:"+sign);

//OLeaidS1JvxuMvnyHOwuJ+uX5qY= }

/** * [Hmac-SHA1 签名算法] * 签名方法 * * @return [签名值] * @String encryptText [加密字符源串] * @String encryptKey [加密密钥] */ public static String getSign(String encryptText, String accessKeySecret) throws Exception { byte[] data = accessKeySecret.getBytes(ENCODING); SecretKey secretKey = new SecretKeySpec(data, MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(secretKey); byte[] text = encryptText.getBytes(ENCODING); byte[] digest = mac.doFinal(text); return new String(Base64.encodeBase64(digest),"UTF-8"); }

/**
* 待签名字符串
* @param map
* @return
*/
public static String getStringToSign(Map<String, String> map,String hTTPMethod) throws UnsupportedEncodingException {
LOG.info("start*******************************************getStringToSign()");
//构造规范化字符串
List<String> list = new ArrayList<>(map.keySet());
//按字符串自然大小排序
Collections.sort(list);
//拼接字符串
StringBuilder stringBuilder = new StringBuilder();
for (String p : list) {
stringBuilder.append(percentEncode(p))
.append("=")
.append(percentEncode(map.get(p)))
.append("&");
}
System.out.println("stringBuilder.toString():"+stringBuilder.toString());
String stringToSign=
hTTPMethod + "&" +
percentEncode("/") + "&" +
percentEncode(stringBuilder.toString());
System.out.println("stringToSign:"+stringToSign);
LOG.info("end*******************************************getStringToSign()");
return stringToSign;
}
/**
* 待签名字符串参数的名称和值分别用UTF-8字符集进行URL编码
*/
private static String percentEncode(String value) throws UnsupportedEncodingException {
return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~").replace("/", "%2F") : null; }

}