[Java] 纯文本查看 复制代码 java示例
/**
* 获取get请求参数字符串
*
* @param param get/delete请求参数map
* @return
*/
public static String getRequestParamString(Map<String, String> param) {
if (MapUtils.isEmpty(param)) {
return "";
}
StringBuilder sb = new StringBuilder(1024);
SortedMap<String, String> map = new TreeMap<>(param);
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = StringUtils.isBlank(entry.getValue()) ? "" : entry.getValue();
sb.append(key).append('=').append(urlEncode(value)).append('&');
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("UTF-8 encoding not supported!");
}
}
/**
* 签名
*/
public static String sign(SignVo signVo) {
if (signVo.getRequestParam() == null) {
signVo.setRequestParam("");
}
String str = signVo.getAccessKey() + signVo.getReqTime() + signVo.getRequestParam();
return actualSignature(str, signVo.getSecretKey());
}
public static String actualSignature(String inputStr, String key) {
Mac hmacSha256;
try {
hmacSha256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secKey =
new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSha256.init(secKey);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("No such algorithm: " + e.getMessage());
} catch (InvalidKeyException e) {
throw new RuntimeException("Invalid key: " + e.getMessage());
}
byte[] hash = hmacSha256.doFinal(inputStr.getBytes(StandardCharsets.UTF_8));
return Hex.encodeHexString(hash);
}
@Getter
@Setter
public static class SignVo {
private String reqTime;
private String accessKey;
private String secretKey;
private String requestParam; //get请求参数根据字典顺序排序,使用&拼接字符串,post为json字符串
} |