JAVA版
// 计算签名
private static final String ENCODING = "UTF-8";
private static final String ALGORITHM = "HmacSHA1";
Mac mac = Mac.getInstance(ALGORITHM);
String text = "你需要计算的内容";
String acKey = "一般为你的接口accesskey";
mac.init(new SecretKeySpec(acKey.getBytes(ENCODING), ALGORITHM));
byte[] signData = mac.doFinal(text.getBytes(ENCODING));
String signature = new String(Base64.encodeBase64(signData));
Python版
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import requests
import json
import traceback
import urllib
import hashlib
import time
import uuid
import string
import datetime
from hashlib import sha1
import base64
import hmac
from hmac import new as hmac
#授权
def hash_hmac(ac_key, text):
return str(hmac(ac_key, text, sha1).digest().encode('base64')[:-1])
关于API参数URL编码需要注意的问题:
JAVA的URLEncoder.encode函数默认对”/”进行编码,而python的URL编码函数urllib.quote默认不会对”/”进行编码,所以需要对该函数进行参数指定,如下实现。
urllib.quote("/",safe='')
关于GMT时间获取的实现:
Python版
time_format_str = datetime.datetime.utcnow().isoformat()
time_format_str = time_format_str.split(".")[0]+"Z"
JAVA版
private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private static String formatIso8601Date(Date date) {
SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df.format(date);
}