官方服務API校驗規範__平台介紹_數加平台介紹-阿裏雲
歡迎使用數加API
您可以通過調用API來實現對您在數加訂購的官方服務的調用
您可以通過發起HTTPS請求來調用API,首先您需要擁有AccessKey( 點擊這裏創建和管理您的AccessKey),AccessKey相當於您訪問阿裏雲產品的口令,擁有您完整的權限,請您妥善保管、避免泄露,並定期更換您的AccessKey!
API整體的校驗規則
API簽名包含 公共請求頭(HTTP協議header參數)、URL(規範資源)、Body
Authorization = Dataplus AccessKeyId + ":" + SignatureSignature = Base64( HMAC-SHA1( AccessSecret, UTF-8-Encoding-Of(StringToSign) ) )StringToSign =//HTTP協議headerHTTP-Verb + "n" + //GET|POST|PUT...Accept + "n" +Content-MD5 + "n" + //Body的MD5值放在此處Content-Type + "n" +Date + "n" +url
簽名計算方法
API請求使用標準的Authorization頭來簽名自己的請求,請求格式如下:
Authorization: Dataplus AccessKeyId:Signature
簽名算法遵循RFC 2104HMAC-SHA1規範,要簽名的元素是請求自身的一些參數,由於每個API請求基本不同,所以簽名的結果也不盡相同。
公共請求頭計算簽名
HTTP協議header
計算簽名必須包含參數,Accept、Content-Type、Date的值(Content-Length不計入簽名),並按順序排列;若值不存在則以”n”補齊
| 名稱 | 含義 | 類型 | 默認值 |
|---|---|---|---|
| Authorization | 用於驗證請求合法性的認證信息,采用AccessKeyId:Signature的形式。 | 字符串 | 默認值:無 |
| Content-Type | RFC 2616中定義的HTTP請求內容類型。 | 類型:字符串 | 默認值:無 |
| Date | HTTP 1.1協議中規定的GMT時間,例如:Wed, 05 Sep. 2012 23:00:00 GMT | 字符串 | 無 |
| Accept | 客戶端需要的返回值類型。 | 類型:字符串 | 無 |
URL
完整的URL,比如https://127.0.0.1:808/xxx/yyy?a=1&c=2
URL: '/xxx/yyy?a=1&c=2'
Case
- Node.js
var request = require('request');var url = require('url');var crypto = require('crypto');var date = new Date().toUTCString()// 這裏填寫AK和請求var ak_id = 'NNV..........5jv';var ak_secret = 'FGs.....................3Zu';var options = {url : 'https://shujuapi.aliyun.com/org_code/service_code/api_name?param1=xxx¶m2=xxx',method: 'GET',body: '',headers: {'accept': 'application/json','content-type': 'application/json','date': date,'Authorization': ''}};// 這裏填寫AK和請求md5 = function(buffer) {var hash;hash = crypto.createHash('md5');hash.update(buffer);return hash.digest('base64');};sha1 = function(stringToSign, secret) {var signature;return signature = crypto.createHmac('sha1', secret).update(stringToSign).digest().toString('base64');};// step1: 組stringToSign [StringToSign = #{method}\n#{accept}\n#{data}\n#{contentType}\n#{date}\n#{action}]var body = options.body || '';var bodymd5;if(body === void 0 || body === ''){bodymd5 = body;} else {bodymd5 = md5(new Buffer(body));}console.log(bodymd5)var stringToSign = options.method + "n" + options.headers.accept + "n" + bodymd5 + "n" + options.headers['content-type'] + "n" + options.headers.date + "n" + url.parse(options.url).path;console.log("step1-Sign string:", stringToSign);// step2: 加密 [Signature = Base64( HMAC-SHA1( AccessSecret, UTF-8-Encoding-Of(StringToSign) ) )]var signature = sha1(stringToSign, ak_secret);// console.log("step2-signature:", signature);// step3: 組authorization header [Authorization = Dataplus AccessKeyId + ":" + Signature]var authHeader = "Dataplus " + ak_id + ":" + signature;console.log("step3-authorization Header:", authHeader);options.headers.Authorization = authHeader;console.log('authHeader', authHeader);// step4: send requestfunction callback(error, response, body) {if (error) {console.log("error", error)}console.log("step4-response body:", response.statusCode, body)}request(options, callback);
- Java
package com.alibaba.vo;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;import java.security.MessageDigest;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Locale;import javax.crypto.spec.SecretKeySpec;import sun.misc.BASE64Encoder;import javax.crypto.Mac;@SuppressWarnings("restriction")public class AESDecode {/** 計算MD5+BASE64*/public static String MD5Base64(String s) {if (s == null)return null;String encodeStr = "";byte[] utfBytes = s.getBytes();MessageDigest mdTemp;try {mdTemp = MessageDigest.getInstance("MD5");mdTemp.update(utfBytes);byte[] md5Bytes = mdTemp.digest();BASE64Encoder b64Encoder = new BASE64Encoder();encodeStr = b64Encoder.encode(md5Bytes);} catch (Exception e) {throw new Error("Failed to generate MD5 : " + e.getMessage());}return encodeStr;}/** 計算 HMAC-SHA1*/public static String HMACSha1(String data, String key) {String result;try {SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");Mac mac = Mac.getInstance("HmacSHA1");mac.init(signingKey);byte[] rawHmac = mac.doFinal(data.getBytes());result = (new BASE64Encoder()).encode(rawHmac);} catch (Exception e) {throw new Error("Failed to generate HMAC : " + e.getMessage());}return result;}/** 等同於javaScript中的 new Date().toUTCString();*/public static String toGMTString(Date date) {SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));return df.format(date);}/** 發送POST請求*/public static String sendPost(String url, String body, String ak_id, String ak_secret) throws Exception {PrintWriter out = null;BufferedReader in = null;String result = "";int statusCode = 200;try {URL realUrl = new URL(url);/** http header 參數*/String method = "POST";String accept = "json";String content_type = "application/json";String path = realUrl.getFile();String date = toGMTString(new Date());// 1.對body做MD5+BASE64加密String bodyMd5 = MD5Base64(body);String stringToSign = method + "n" + accept + "n" + bodyMd5 + "n" + content_type + "n" + date + "n"+ path;// 2.計算 HMAC-SHA1String signature = HMACSha1(stringToSign, ak_secret);// 3.得到 authorization headerString authHeader = "Dataplus " + ak_id + ":" + signature;// 打開和URL之間的連接URLConnection conn = realUrl.openConnection();// 設置通用的請求屬性conn.setRequestProperty("accept", accept);conn.setRequestProperty("content-type", content_type);conn.setRequestProperty("date", date);conn.setRequestProperty("Authorization", authHeader);// 發送POST請求必須設置如下兩行conn.setDoOutput(true);conn.setDoInput(true);// 獲取URLConnection對象對應的輸出流out = new PrintWriter(conn.getOutputStream());// 發送請求參數out.print(body);// flush輸出流的緩衝out.flush();// 定義BufferedReader輸入流來讀取URL的響應statusCode = ((HttpURLConnection)conn).getResponseCode();if(statusCode != 200) {in = new BufferedReader(new InputStreamReader(((HttpURLConnection)conn).getErrorStream()));} else {in = new BufferedReader(new InputStreamReader(conn.getInputStream()));}String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {e.printStackTrace();} finally {try {if (out != null) {out.close();}if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}if (statusCode != 200) {throw new IOException("nHttp StatusCode: "+ statusCode + "nErrorMessage: " + result);}return result;}/** GET請求*/public static String sendGet(String url, String ak_id, String ak_secret) throws Exception {String result = "";BufferedReader in = null;int statusCode = 200;try {URL realUrl = new URL(url);/** http header 參數*/String method = "GET";String accept = "json";String content_type = "application/json";String path = realUrl.getFile();String date = toGMTString(new Date());// 1.對body做MD5+BASE64加密// String bodyMd5 = MD5Base64(body);String stringToSign = method + "n" + accept + "n" + "" + "n" + content_type + "n" + date + "n" + path;// 2.計算 HMAC-SHA1String signature = HMACSha1(stringToSign, ak_secret);// 3.得到 authorization headerString authHeader = "Dataplus " + ak_id + ":" + signature;// 打開和URL之間的連接URLConnection connection = realUrl.openConnection();// 設置通用的請求屬性connection.setRequestProperty("accept", accept);connection.setRequestProperty("content-type", content_type);connection.setRequestProperty("date", date);connection.setRequestProperty("Authorization", authHeader);connection.setRequestProperty("Connection", "keep-alive");// 建立實際的連接connection.connect();// 定義 BufferedReader輸入流來讀取URL的響應statusCode = ((HttpURLConnection)connection).getResponseCode();if(statusCode != 200) {in = new BufferedReader(new InputStreamReader(((HttpURLConnection)connection).getErrorStream()));} else {in = new BufferedReader(new InputStreamReader(connection.getInputStream()));}String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {e.printStackTrace();} finally {try {if (in != null) {in.close();}} catch (Exception e) {e.printStackTrace();}}if (statusCode != 200) {throw new IOException("nHttp StatusCode: "+ statusCode + "nErrorMessage: " + result);}return result;}public static void main(String[] args) throws Exception {// 發送POST請求示例String ak_id1 = "NMV.............5jv"; //用戶akString ak_secret1 = "Fgs...............3zu"; // 用戶ak_secretString url = "https://shujuapi.aliyun.com/org_code/service_code/api_name";String body = "{"param1": "xxx", "param2":"xxx"}";System.out.println("response body:" + sendPost(url, body, ak_id, ak_secret));// 發送GET請求String ak_id1 = "NMV.............5jv"; //用戶akString ak_secret1 = "Fgs...............3zu"; // 用戶ak_secretString url1 = "https://shujuapi.aliyun.com/org_code/service_code/api_name?param1=xxx¶m2=xxx";System.out.println("response body:" + sendGet(url1, ak_id1, ak_secret1));}}
- PHP
<?php$akId = "*************";$akSecret = "******************";//更新api信息$url = "https://shujuapi.aliyun.com/org_code/service_code/api_name?param1=xxx¶m2=xxx";$body = array('requests' => array("asr", "ds"));$options = array('http' => array('header' => array('accept'=> "application/json",'content-type'=> "application/json",'date'=> gmdate("D, d M Y H:i:s GMT"),'authorization' => ''),'method' => "GET", //可以是 GET, POST, DELETE, PUT'content' => json_encode($body)));$http = $options['http'];$header = $http['header'];$urlObj = parse_url($url);if(empty($urlObj["query"]))$path = $urlObj["path"];else$path = $urlObj["path"]."?".$urlObj["query"];$body = $http['content'];if(empty($body))$bodymd5 = $body;else$bodymd5 = base64_encode(md5($body,true));$stringToSign = $http['method']."n".$header['accept']."n".$bodymd5."n".$header['content-type']."n".$header['date']."n".$path;$signature = base64_encode(hash_hmac("sha1",$stringToSign,$akSecret, true));$authHeader = "Dataplus "."$akId".":"."$signature";$options['http']['header']['authorization'] = $authHeader;$options['http']['header'] = implode(array_map(function($key, $val){return $key.":".$val."rn";},array_keys($options['http']['header']),$options['http']['header']));$context = stream_context_create($options);$file = file_get_contents($url, false, $context );echo($file);?>
- Python 2.7
#!/usr/bin/python# -*- coding:utf-8 -*-from urlparse import urlparseimport datetimeimport base64import hmacimport hashlibimport jsonimport urllib2def get_current_date():date = datetime.datetime.strftime(datetime.datetime.utcnow(), "%a, %d %b %Y %H:%M:%S GMT")return datedef to_md5_base64(strBody):hash = hashlib.md5()hash.update(body)return hash.digest().encode('base64').strip()def to_sha1_base64(stringToSign, secret):hmacsha1 = hmac.new(secret, stringToSign, hashlib.sha1)return base64.b64encode(hmacsha1.digest())ak_id = '<用戶的AK_ID>'ak_secret = '<用戶的AK_SECRET>'options = {'url': '<請求的url>','method': 'POST','body': json.dumps({"name": "hello"}, separators=(',', ':')),'headers': {'accept': 'application/json','content-type': 'application/json','date': get_current_date(),'authorization': ''}}# options = {# 'url': '<請求的url>',# 'method': 'GET',# 'headers': {# 'accept': 'application/json',# 'content-type': 'application/json',# 'date': get_current_date(), # 'Sat, 07 May 2016 08:19:52 GMT', # get_current_date(),# 'authorization': ''# }# }body = ''if 'body' in options:body = options['body']print bodybodymd5 = ''if not body == '':bodymd5 = to_md5_base64(body)print bodymd5urlPath = urlparse(options['url'])if urlPath.query != '':urlPath = urlPath.path + "?" + urlPath.queryelse:urlPath = urlPath.pathstringToSign = options['method'] + 'n' + options['headers']['accept'] + 'n' + bodymd5 + 'n' + options['headers']['content-type'] + 'n' + options['headers']['date'] + 'n' + urlPathsignature = to_sha1_base64(stringToSign, ak_secret)print stringToSignauthHeader = 'Dataplus ' + ak_id + ':' + signatureoptions['headers']['authorization'] = authHeaderprint authHeaderrequest = Nonemethod = options['method']url = options['url']print methodprint urlif 'GET' == method or 'DELETE' == method:request = urllib2.Request(url)elif 'POST' == method or 'PUT' == method:request = urllib2.Request(url, body)request.get_method = lambda: methodfor key, value in options['headers'].items():request.add_header(key, value)try:conn = urllib2.urlopen(request)response = conn.read()print responseexcept urllib2.HTTPError, e:print e.read()raise SystemExit(e)
最後更新:2016-12-13 10:02:37
上一篇:
公眾趨勢分析服務協議__相關協議_平台介紹_數加平台介紹-阿裏雲
下一篇:
DataIDE示例教程__大數據開發DataIDE_數加體驗館_數加平台介紹-阿裏雲
批量刪除消息__隊列接口規範_API使用手冊_消息服務-阿裏雲
修改RDS實例訪問模式__實例管理_API 參考_雲數據庫 RDS 版-阿裏雲
項目空間的權限管理__安全相關語句匯總_安全指南_大數據計算服務-阿裏雲
人工智能爆發前夜,亞馬遜、微軟、阿裏雲們做了什麼?
修改訂閱對象__數據訂閱_用戶指南_數據傳輸-阿裏雲
刪除應用實例__應用API列表_API參考_容器服務-阿裏雲
數據轉發到RDS中__規則引擎_控製台使用手冊_阿裏雲物聯網套件-阿裏雲
查看線程棧__性能監控_用戶指南(Linux)_數據管理-阿裏雲
修改HTTP頭信息__配置操作接口_API 手冊_CDN-阿裏雲
授權賬號權限__賬號管理_API 參考_雲數據庫 RDS 版-阿裏雲
相關內容
常見錯誤說明__附錄_大數據計算服務-阿裏雲
發送短信接口__API使用手冊_短信服務-阿裏雲
接口文檔__Android_安全組件教程_移動安全-阿裏雲
運營商錯誤碼(聯通)__常見問題_短信服務-阿裏雲
設置短信模板__使用手冊_短信服務-阿裏雲
OSS 權限問題及排查__常見錯誤及排除_最佳實踐_對象存儲 OSS-阿裏雲
消息通知__操作指南_批量計算-阿裏雲
設備端快速接入(MQTT)__快速開始_阿裏雲物聯網套件-阿裏雲
查詢API調用流量數據__API管理相關接口_API_API 網關-阿裏雲
使用STS訪問__JavaScript-SDK_SDK 參考_對象存儲 OSS-阿裏雲