Groovy code example

Updated at:
Copy as MD

This topic provides a Groovy code example for calling the Filing Service API.

You can save the following code as a Groovy script and run it.

@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){ // The encode method
URLEncoder.encode(s as String, 'utf-8').replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
}
def accessKey='testKey'// Your AccessKey ID.
def accessSecret='testSecre'// The AccessKey secret that corresponds to your AccessKey ID. You can find it at https://ak-console.aliyun.com/#/accesskey.
def HTTPMethod='GET'
def date=new Date()
def params=new TreeMap<String,String>()// Parameters
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)// After confirming the URL is correct, uncomment the following lines to test it.
//println u.getText('utf-8')