Aliyun API Appendix: How to invoke an interface

Source: Internet
Author: User
Tags final hmac http request json sha1 sort aliyun

  How to invoke an interface

Calls to the ECS service interface are made by sending an HTTP request to the ECS server (which can be sent over an HTTP or HTTPS protocol), and obtaining the process by which the ECS service responds to the request. The ECS server, after receiving a user request, makes the necessary authentication and parameter validation of the request, submits and completes the action according to the specified parameters of the request after all successful validation, and returns the processing result to the caller as an HTTP response.

  Request composition

The request consists of the following sections:

HTTP method-all interfaces of the current ECS service support only calls to get methods.

The service address of the request url--request, the name of the action to be performed, the action arguments, and the public request parameters are included in the requested URL.

Service-side address: ECS Service domain name is http://ecs.aliyuncs.com/and https://ecs.aliyuncs.com/. To ensure the security of the request, you are strongly recommended to use the HTTPS channel. (HTTPS joins the SSL layer to encrypt communications, preventing traffic from being intercepted and causing sensitive information to leak.) )

Action Name: Each interface needs to specify the name of the action to be performed, that is, the action parameter.

Operation parameters: Depending on the operation to be performed, different operation parameters need to be passed in, as described in each interface.

Common Request parameters: parameters that include timestamps, signature information, and so on, for each request.

In order for the server side to properly authenticate the user and authorize the request to execute, the request is signed before committing. The rules for signing see the signature mechanism section.

The response results are returned when the service side completes the request processing. The response results are divided into successful results and error messages, and the format description is shown in the section return results. The client can parse the message body of the response and get execution results.

Call Example

Take the Describeregions interface for example:

The corresponding action is describeregions, which is used to query the list of available geographies because the interface has no custom parameters, so just add a common request parameter (except for the signature, which needs to be computed later by the signature algorithm). After the parameters have been added, the requested URL is (for readability, here is the URL before URL encoding):

http://ecs.aliyuncs.com/? timestamp=2016-02-23t12:46:24z&format=xml&accesskeyid=testid&action=describeregions& signaturemethod=hmac-sha1&signaturenonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&version=2014-05-26& signatureversion=1.0

According to the signature calculation rule, the canonical request string (canonicalized Query strings) is constructed first, as follows:

Accesskeyid=testid&action=describeregions&format=xml&signaturemethod=hmac-sha1&signaturenonce= 3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&signatureversion=1.0&timestamp=2016-02-23t12%3a46%3a24z& Version=2014-05-26

The string stringtosign value for the signature is then constructed:

get&%2f&accesskeyid%3dtestid%26action%3ddescriberegions%26format%3dxml%26signaturemethod%3dhmac-sha1% 26signaturenonce%3d3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf%26signatureversion%3d1.0%26timestamp%3d2016-02-23t12% 253a46%253a24z%26version%3d2014-05-26

The following Java sample code demonstrates how to add a common request parameter, construct a normalized request string with a request parameter, and construct a stringtosign string. The example assumes that all request parameters are placed in a map object and that the access Key ID used is "TestID".

Final String Http_method = "get";

Map parameters = new HashMap ();

Join Request Parameters

Parameters.put ("Action", "describeregions");

Parameters.put ("Version", "2014-05-26");

Parameters.put ("Accesskeyid", "TestID");

Parameters.put ("TimeStamp", Formatiso8601date (New Date ());

Parameters.put ("SignatureMethod", "HMAC-SHA1");

Parameters.put ("Signatureversion", "1.0");

Parameters.put ("Signaturenonce", Uuid.randomuuid (). toString ());

Parameters.put ("Format", "XML");

To sort a parameter

string[] Sortedkeys = Parameters.keyset (). ToArray (New string[]{});

Arrays.sort (Sortedkeys);

Final String SEPARATOR = "&";

Generate Stringtosign String

StringBuilder stringtosign = new StringBuilder ();

Stringtosign.append (Http_method). Append (SEPARATOR);

Stringtosign.append (Percentencode ("/")). Append (SEPARATOR);

StringBuilder canonicalizedquerystring = new StringBuilder ();

for (String Key:sortedkeys) {

Here, note that the key and value are encoded

Canonicalizedquerystring.append ("&")

. Append (Percentencode (key)). Append ("=")

. Append (Percentencode (Parameters.get (key));

}

Here, note the encoding of the canonicalizedquerystring.

Stringtosign.append (Percentencode (

Canonicalizedquerystring.tostring (). substring (1));

It should be noted that the timestamp parameter requires compliance with the ISO8601 specification and that the UTC time is used, otherwise an error is encountered. The following example code demonstrates how to generate a timestamp string that conforms to a specification:

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 (New SimpleTimeZone (0, "GMT"));

return Df.format (date);

}

The necessary encoding is required to generate the normalized request string (the canonicalizedquerystring variable in the example) and sringtosign. The coded rules are described in detail in the signature mechanism section. The following example code illustrates the coded algorithm:

private static final String ENCODING = "UTF-8";

private static string Percentencode (String value) throws Unsupportedencodingexception {

return value!= null? Urlencoder.encode (value, ENCODING). Replace ("+", "%20"). Replace ("*", "%2a"). Replace ("%7e", "~"): null;

}

Assuming the access key ID is "TestID" and the access key secret is "Testsecret", the key used to compute the HMAC is "testsecret&", and the resulting signature value is:

Ct9x0vtwr86fnwsnsc6v8ygojue=

Sample code for calculating signatures (Java):

The following is a sample code that calculates the signature

Final String algorithm = "HmacSHA1";

Final String ENCODING = "UTF-8";

Key = "testsecret&";

Mac Mac = mac.getinstance (algorithm);

Mac.init (New Secretkeyspec (Key.getbytes (ENCODING), algorithm));

byte[] SignData = mac.dofinal (Stringtosign.getbytes (ENCODING));

String signature = new String (Base64.encodebase64 (SignData));

After adding the signature parameters, follow the RFC3986 rule to get the URL encoding

Http://ecs.aliyuncs.com/?SignatureVersion=1.0&Action=DescribeRegions&Format=XML&SignatureNonce= 3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&version=2014-05-26&accesskeyid=testid&signature= ct9x0vtwr86fnwsnsc6v8ygojue%3d&signaturemethod=hmac-sha1&timestamp=2016-02-23t12%3a46%3a24z

Next, the HTTP request is sent to the URL address above, and the results of the response from the ECS Server (sample) are obtained:

By parsing This XML result, you can get a list of all available geographical IDs and LocalName. If the format parameter is specified as JSON when the request is submitted, the format of the returned result is in JSON format.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.