本文提供了調用備案服務 API 接口的 Groovy 版代碼示例。
您可以把以下代碼保存為一個 Groovy 腳本執行。
@GrabConfig(systemClassLoader=true)
@Grab('commons-codec:commons-codec:1.10')
import org.apache.commons.codec.binary.*
import org.apache.commons.codec.digest.HmacUtils
System.setProperty("user.timezone", "UTC")
TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
def percentEncode(s){ //encode 方法
URLEncoder.encode(s as String, 'utf-8').replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
}
def accessKey='testKey'//您的 key
def accessSecret='testSecre'//您的 key 對應的 secret,您可以在 https://ak-console.aliyun.com/#/accesskey 查找
def HTTPMethod='GET'
def date=new Date()
def params=new TreeMap<String,String>()//參數
def d=new Random()
params.put('Timestamp',date.format("yyyy-MM-dd'T'HH:mm:ss'Z'"))
params.put('Format','xml')
params.put('AccessKeyId',accessKey)
params.put('Action','GetBsnBySn')
params.put('SignatureMethod','HMAC-SHA1')
params.put('RegionId','cn-beijing')
params.put('Version','2015-05-12')
params.put('SignatureNonce',(d.nextInt(Integer.MAX_VALUE) as String) + (date.time as String))
params.put('sn','1131-5341-315666-5234-233')
params.put('SignatureVersion','1.0')
def canonicalizedQueryString=params.collect{key,value->
key+'='+percentEncode(value)
}
println canonicalizedQueryString
def stringToSign=HTTPMethod+'&'+percentEncode('/')+'&'+ percentEncode (canonicalizedQueryString)
println stringToSign
def sign=Base64.encodeBase64String(HmacUtils.hmacSha1(accessSecret+'&',stringToSign))
println sign
def url= 'http://bsn.aliyuncs.com/?'+canonicalizedQueryString+'&Signature='+sign
println url
//def u=new URL(url)//確認無誤后可以打開該 URL 進行測試
//println u.getText('utf-8')