调用阿里云API 的demo示例(java/python)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调用阿里云API 的demo示例(java/python)相关的知识,希望对你有一定的参考价值。

Java 示例

 

// 创建DefaultAcsClient实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile(vo.getAliRegionId(),AliAccessKeyId,AliAccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        // 创建API请求并设置参数
        DescribeVirtualBorderRoutersRequest request = new DescribeVirtualBorderRoutersRequest();

        //组装filter数据
        List<DescribeVirtualBorderRoutersRequest.Filter> list = new ArrayList<DescribeVirtualBorderRoutersRequest.Filter>();
        DescribeVirtualBorderRoutersRequest.Filter filter = new DescribeVirtualBorderRoutersRequest.Filter();
        filter.setKey(AliEdgeRouterConstant.FILTER_KEY);
        List list1 = new ArrayList();
        list1.add(vo.getVbrUuid());
        filter.setValues(list1);
        list.add(filter);

        request.setFilters(list);


        DescribeVirtualBorderRoutersResponse response ;
        try{
            response = client.getAcsResponse(request);

            DescribeVirtualBorderRoutersResponse.VirtualBorderRouterType virtualBorderRouterType = new DescribeVirtualBorderRoutersResponse.VirtualBorderRouterType();
            virtualBorderRouterType = response.getVirtualBorderRouterSet().get(0);

            routerInventory.setName(virtualBorderRouterType.getName());
            routerInventory.setVbrUuid(virtualBorderRouterType.getVbrId());
            routerInventory.setDescription(virtualBorderRouterType.getDescription());
            routerInventory.setCreateDate(vo.getCreateDate());
            routerInventory.setVlan(vo.getVlan());
            routerInventory.setAliAccountUuid(vo.getAliAccountUuid());
            routerInventory.setAliRegionId(vo.getAliRegionId());


            inventory.setAccessPoint(virtualBorderRouterType.getAccessPointId());
            inventory.setStatus(virtualBorderRouterType.getStatus());
            inventory.setPhysicalLineOwerUuid(virtualBorderRouterType.getPhysicalConnectionOwnerUid());
            inventory.setLocalGatewayIp(virtualBorderRouterType.getLocalGatewayIp());
            inventory.setPeerGatewayIp(virtualBorderRouterType.getPeerGatewayIp());
            inventory.setPeeringSubnetMask(virtualBorderRouterType.getPeeringSubnetMask());


        }catch (ClientException e){
            e.printStackTrace();
            if(e.getErrCode().equals("InvalidAccessKeyId.NotFound")){
                flag = false;
            }else{
                throw new ApiMessageInterceptionException(argerr(e.getMessage()));
            }

        }

  Python示例

sdk:

def ModifyVirtualBorderRouterAttribute(key, value, RegionId, VBRId, LocalGatewayIp, PeerGatewayIp, PeeringSubnetMask, Name, Description):

    from aliyunsdkvpc.request.v20160428 import ModifyVirtualBorderRouterAttributeRequest
    request = ModifyVirtualBorderRouterAttributeRequest.ModifyVirtualBorderRouterAttributeRequest()
    request.set_accept_format(‘json‘)
    request.set_VbrId(VBRId)
    request.set_LocalGatewayIp(LocalGatewayIp)
    request.set_PeerGatewayIp(PeerGatewayIp)
    request.set_PeeringSubnetMask(PeeringSubnetMask)
    request.set_Name(Name)
    request.set_Description(Description)
    client.set_access_key(key)
    client.set_access_secret(value)
    client.set_region_id(RegionId)

    reponse = client.do_action_with_exception(request)
    return reponse  

API:

 

  1 import os, sys
  2 import hashlib
  3 import hmac
  4 import base64
  5 import urllib
  6 import time
  7 import uuid
  8 import requests
  9 
 10 
 11 def get_iso8601_time():
 12     ‘‘‘返回iso8601格式的时间‘‘‘
 13     TIME_ZONE = "GMT"
 14     FORMAT_ISO8601 = "%Y-%m-%dT%H:%M:%SZ"
 15     return time.strftime(FORMAT_ISO8601, time.gmtime())
 16 
 17 
 18 def get_uuid():
 19     ‘‘‘返回uuid‘‘‘
 20     return str(uuid.uuid4())
 21 
 22 
 23 def get_parameters(user_param, Action, AccessKeyId, Version):
 24     ‘‘‘
 25     拼接参数字典
 26     user_param: {"RegionId":"cn-beijing", "LoadBalancerName":"test-node1", "AddressType":"intranet", "VSwitchId":"vsw-2zevjlczuvp2mkhhch12x"}
 27     Action操作例如:CreateLoadBalancer
 28     AccessKeyId:access key ID
 29     Version: 接口的版本
 30     ‘‘‘
 31     parameters = {}
 32     parameters[HTTPMethod] = GET
 33     parameters[AccessKeyId] = AccessKeyId
 34     parameters[Format] = json
 35     parameters[Version] = Version
 36     parameters[SignatureMethod] = HMAC-SHA1
 37     parameters[Timestamp] = get_iso8601_time()
 38     parameters[SignatureVersion] = 1.0
 39     parameters[SignatureNonce] = get_uuid()
 40     parameters[Action] = Action
 41     for (k, v) in sorted(user_param.items()):
 42         parameters[k] = v
 43     return parameters
 44 
 45 
 46 def get_param(parameters):
 47     ‘‘‘把公共参数拼接成字符串‘‘‘
 48     param_str = ‘‘
 49     for (k, v) in sorted(parameters.items()):
 50         param_str += "&" + urllib.quote(k, safe=‘‘) + "=" + urllib.quote(v, safe=‘‘)
 51     param_str = param_str[1:]
 52     return param_str
 53 
 54 
 55 def get_StringToSign(parameters, param_str):
 56     ‘‘‘拼接生成签名的字符串‘‘‘
 57     StringToSign = parameters[HTTPMethod] + "&%2F&" + urllib.quote(param_str, safe=‘‘)
 58     return StringToSign
 59 
 60 
 61 def get_signature(StringToSign, AccessKeySecret):
 62     ‘‘‘构建签名‘‘‘
 63     h = hmac.new(AccessKeySecret, StringToSign, hashlib.sha1)
 64     signature = base64.encodestring(h.digest()).strip()
 65     return signature
 66 
 67 
 68 def build_request(server_url, param_str, signature, AccessKeySecret):
 69     ‘‘‘拼接url并进行请求‘‘‘
 70     Signature = "Signature=" + urllib.quote(signature)
 71     param = param_str + "&" + Signature
 72     request_url = server_url + param
 73     s = requests.get(request_url)
 74     print s.content
 75     print s
 76     return s
 77 
 78 def get_regions(server_url, Action, user_param, AccessKeySecret, AccessKeyId, Version):
 79     ‘‘‘对请求进行模块
 80     server_url: slb.aliyun.com
 81     Action = ‘DescribeRegions‘
 82     AccessKeySecret, AccessKeyId:也就是ak
 83     user_param = {‘LoadBalancerId‘: ‘lb-2zekxu2elibyexxoo9hlw‘}
 84     Version:例如slb的版本是2014-05-15,每个服务都不相同
 85     ‘‘‘
 86     server_url = https:// + server_url + /?
 87     AccessKeySecret = AccessKeySecret
 88     AccessKeyId = AccessKeyId
 89     parameters = get_parameters(user_param, Action, AccessKeyId, Version)
 90     param_str = get_param(parameters)
 91     StringToSign = get_StringToSign(parameters, param_str)
 92     signature = get_signature(StringToSign, AccessKeySecret + &)
 93     Message = build_request(server_url, param_str, signature, AccessKeySecret)
 94     return Message
 95 
 96 
 97 
 98 create slb
 99 Action = DescribeRegions
100 user_param = {}
101 server_url = vpc.aliyuncs.com
102 Version = 2016-04-28
103 AccessKeySecret=EzuF6gOmgMgaagzvKOXeMRP6m92zB9
104 AccessKeyId=LTAI0iQLAL16wPTF
105 message = get_regions(server_url, Action, user_param, AccessKeySecret, AccessKeyId, Version)
106 print "======================%s" %message
107 print "********************%s" %message.content

 

以上是关于调用阿里云API 的demo示例(java/python)的主要内容,如果未能解决你的问题,请参考以下文章

Powershell 调用阿里云 云解析API 实现动态域名解析

阿里云调用 API 服务后返回啥结果

各位大神,Python怎么调用阿里云API

各位大神,Python怎么调用阿里云API

阿里云 短信消息api 示例 (附:阿里云控制台的消息服务,集成到codeigniter )

PYTHON创蓝253云通讯平台国际短信API接口DEMO