計算 HMAC-SHA1 阿里雲訊息佇列RocketMQ版簽名機制案例以及http呼叫介面案例
阿新 • • 發佈:2021-07-14
使用請求引數構造規範化的請求字串
private static final String ENCODING = "UTF-8"; private static String percentEncode(String value) throws UnsupportedEncodingException { return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null; }
使用UTC時間按照ISO 8601標準,格式為YYYY-MM-DDThh:mm:ss
Date date = new Date(); System.out.println("本地時間Date: " + date); TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); df.setTimeZone(tz); //獲取時區 String nowAsISO = df.format(date);
引數排序 (用到的排序方法在上一篇隨筆)
Map<String, String> map = new HashMap<>(); String ti=System.currentTimeMillis()+"";//當隨機數使用 String url="http://ons.cn-shenzhen.aliyuncs.com?"; map.put("Action","OnsRegionList"); map.put("productName","Ons"); map.put("domain","cn-shenzhen"); map.put("Version","2019-02-14"); map.put("AccessKeyId",""); map.put("AccessKeySecret",""); map.put("SignatureMethod","HMAC-SHA1"); map.put("Timestamp",nowAsISO); map.put("SignatureVersion","1.0"); map.put("SignatureNonce",ti); map.put("Format","JSON"); String s = formatUrlMap(map, true);
處理待簽名的引數、簽名
String StringToSign= "GET" + "&" + percentEncode("/") + "&" + percentEncode(s);
String cu = HMACSha1(StringToSign,AccessKeySecret+"&");
將簽名欄位加入排序、進行請求url拼接、發起請求(Jsoup不知道的可以自行百度)
Connection connect = Jsoup.connect(url+s2); System.out.println(connect.ignoreContentType(true).ignoreHttpErrors(true).get());
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.13.1</version> </dependency>
列印結果