本文提供了调用备案服务 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')