771
微信
官方服务API校验规范__平台介绍_数加平台介绍-阿里云
欢迎使用数加API
您可以通过调用API来实现对您在数加订购的官方服务的调用
您可以通过发起HTTPS请求来调用API,首先您需要拥有AccessKey( 点击这里创建和管理您的AccessKey),AccessKey相当于您访问阿里云产品的口令,拥有您完整的权限,请您妥善保管、避免泄露,并定期更换您的AccessKey!
API整体的校验规则
API签名包含 公共请求头(HTTP协议header参数)、URL(规范资源)、Body
Authorization = Dataplus AccessKeyId + ":" + Signature
Signature = Base64( HMAC-SHA1( AccessSecret, UTF-8-Encoding-Of(StringToSign) ) )
StringToSign =
//HTTP协议header
HTTP-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 request
function 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-SHA1
String signature = HMACSha1(stringToSign, ak_secret);
// 3.得到 authorization header
String 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-SHA1
String signature = HMACSha1(stringToSign, ak_secret);
// 3.得到 authorization header
String 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"; //用户ak
String ak_secret1 = "Fgs...............3zu"; // 用户ak_secret
String 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"; //用户ak
String ak_secret1 = "Fgs...............3zu"; // 用户ak_secret
String 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 urlparse
import datetime
import base64
import hmac
import hashlib
import json
import urllib2
def get_current_date():
date = datetime.datetime.strftime(datetime.datetime.utcnow(), "%a, %d %b %Y %H:%M:%S GMT")
return date
def 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 body
bodymd5 = ''
if not body == '':
bodymd5 = to_md5_base64(body)
print bodymd5
urlPath = urlparse(options['url'])
if urlPath.query != '':
urlPath = urlPath.path + "?" + urlPath.query
else:
urlPath = urlPath.path
stringToSign = options['method'] + 'n' + options['headers']['accept'] + 'n' + bodymd5 + 'n' + options['headers']['content-type'] + 'n' + options['headers']['date'] + 'n' + urlPath
signature = to_sha1_base64(stringToSign, ak_secret)
print stringToSign
authHeader = 'Dataplus ' + ak_id + ':' + signature
options['headers']['authorization'] = authHeader
print authHeader
request = None
method = options['method']
url = options['url']
print method
print url
if 'GET' == method or 'DELETE' == method:
request = urllib2.Request(url)
elif 'POST' == method or 'PUT' == method:
request = urllib2.Request(url, body)
request.get_method = lambda: method
for key, value in options['headers'].items():
request.add_header(key, value)
try:
conn = urllib2.urlopen(request)
response = conn.read()
print response
except 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-阿里云