java调用阿里云接口demo

因为修订数据要调用阿里云的服务查询一些数据,遇到不少坑,特此记录。

 
    public static void main(String[] args) throws Exception {
        //根据自己的region更换
        String url = "http://mts.cn-shanghai.aliyuncs.com?";
        String sortStr = buildSortedUrl(null);
        String sign = getSign(sortStr);
        String targetUrl = url + "Signature=" + sign + "&" + sortStr;
        RestTemplate restTemplate = RestTemplateUtils.getRestTemplate();
        JSONObject jsonObject = restTemplate.getForObject(URLDecoder.decode(targetUrl), JSONObject.class);
        System.out.println(jsonObject.toString());
    }

    public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        String MAC_NAME = "HmacSHA1";
        String ENCODING = "UTF-8";
        byte[] data=encryptKey.getBytes(ENCODING);
        //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        //生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        //用给定密钥初始化 Mac 对象
        mac.init(secretKey);
        byte[] text = encryptText.getBytes(ENCODING);
        //完成 Mac 操作
        return mac.doFinal(text);
    }

    public static String encryptBASE64(byte[] key) {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    public static String getISO8601Time(){
        //获取国际标准时间不应该这样搞,没时间,直接-8时区先用了
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.HOUR, -8);
        String timestamp = AmepDateUtils.format(instance.getTime(), AmepDateUtils.SIMPLE);
        java.time.format.DateTimeFormatter dtf1 = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.parse(timestamp,dtf1);
        ZoneOffset offset = ZoneOffset.of("08:00");
        OffsetDateTime date = OffsetDateTime.of(ldt ,offset);
        java.time.format.DateTimeFormatter dtf2 = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String rlt = date.format(dtf2);
        return rlt;
    }

    public static String getSign(String sortUrl) throws Exception {
        String StringToSign = "GET&%2F&" + java.net.URLEncoder.encode(sortUrl);
        byte[] rlt = HmacSHA1Encrypt(StringToSign, "testKey");
        String sig = encryptBASE64(rlt);
        sig = sig.replace("\r", "").replace("\n", "");
        sig = URLEncoder.encode(sig);
        return sig;
    }
    
    public static String buildSortedUrl(String nextPageToken){
        Map<String, String> map = new HashMap<>();
        map.put("Action","ListMediaWorkflowExecutions");
        map.put("MaximumPageSize","5");
        if(StringUtils.isNotBlank(nextPageToken)){
            map.put("NextPageToken",nextPageToken);
        }
        map.put("AccessKeyId","AccessKeyId");
        map.put("Format","JSON");
        map.put("SignatureMethod","Hmac-SHA1");
        map.put("SignatureNonce", UUIDGenerator.genId());
        map.put("SignatureVersion", "1.0");
        map.put("Timestamp", getISO8601TimestampFromDateStr());
        map.put("Version","2014-06-18");
        List<String> sortList = new ArrayList<>();
        for (String key : map.keySet()) {
            sortList.add(key);
        }
        sortList.sort(Comparator.naturalOrder());
        String sortStr = null;
        for(String key : sortList){
            String temp = URLEncoder.encode(key) + "=" + URLEncoder.encode(map.get(key));
            if(sortStr == null){
                sortStr = temp;
            }else{
                sortStr += "&" + temp;
            }
        }
        sortStr.replace("+","%20").replace("*","%2A").replace("%7E","~");
        return sortStr;
    }
上一篇:异常和中断


下一篇:本地进程间通信(五)--信号