博主首页

计算 HMAC-SHA1 阿里云消息队列RocketMQ版签名机制案例以及http调用接口案例

 使用请求参数构造规范化的请求字符串

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>

打印结果

 

posted @ 2021-07-14 10:57  笑~笑  阅读(259)  评论(0编辑  收藏  举报