云服务器内容精选

  • 请求签名与API调用 在工程中引入sdk。 1 2 3 4 5 6 using System; using System.Net; using System.IO; using System.Net.Http; using System.Threading; using APIGATEWAY_SDK; 生成一个新的Signer, 填入AK和SK。 1 2 3 4 5 Signer signer = new Signer(); // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. signer.Key = Environment.GetEnvironmentVariable("HUAWEICLOUD_SDK_AK"); signer.Secret = Environment.GetEnvironmentVariable("HUAWEICLOUD_SDK_SK"); 生成一个新的Request,指定域名、方法名、请求uri和body。 1 2 3 4 //The following example shows how to set the request URL and parameters to query a VPC list. HttpRequest r = new HttpRequest("GET", new Uri("https://{service}.region.example.com/v1/77b6a44cba5**********9a8ff44fd/vpcs?limit=1")); //Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped. r.body = ""; 添加需要签名的其他头域,或者其他用途的头域,如多项目场景中添加X-Project-Id,或者全局服务场景中添加X-Domain-Id。 1 2 //Add header parameters, for example, X-Domain-Id for invoking a global service and X-Project-Id for invoking a project-level service. r.headers.Add("X-Project-Id", "xxx"); 进行签名,执行此函数会生成一个新的HttpWebRequest,并在请求参数中添加用于签名的X-Sdk-Date头和Authorization头。 如果您使用HTTP Client,可以从请求中获取头部信息使用。关于头部信息,请参考AK/SK签名认证算法详解。 1 HttpWebRequest req = signer.Sign(r); 访问API,查看访问结果。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 try { var writer = new StreamWriter(req.GetRequestStream()); writer.Write(r.body); writer.Flush(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); var reader = new StreamReader(resp.GetResponseStream()); Console.WriteLine(reader.ReadToEnd()); } catch (WebException e) { HttpWebResponse resp = (HttpWebResponse)e.Response; if (resp != null) { Console.WriteLine((int)resp.StatusCode + " " + resp.StatusDescription); var reader = new StreamReader(resp.GetResponseStream()); Console.WriteLine(reader.ReadToEnd()); } else { Console.WriteLine(e.Message); } } Console.WriteLine("----------------");
  • 获取SDK 点此下载SDK与Demo。 解压后目录结构如下: 名称 说明 apigateway-signature\Signer.cs SDK代码 apigateway-signature\HttpEncoder.cs sdk-request\Program.cs 签名请求示例代码 csharp.sln 工程文件 licenses\license-referencesource 第三方库license文件
  • 准备环境 获取并安装IDEA 2022.2.1,可至IDEA官方网站下载可执行文件进行安装,或者下载全量压缩包并解压后直接使用。 JDK:Java Development Kit 1.8.111及以上版本,可至Oracle官方下载页面下载。暂不支持Java Development Kit 17或以上版本。 Maven仓地址:https://repo.huaweicloud.com/apache/maven/maven-3/。
  • API调用 示例代码修改调用环境信息后可直接调用。以下以新建工程为例,介绍如何在您的应用中调用SDK进行请求签名。 把API信息替换到HttpClientDemo.java中对应位置。 HttpClientDemo中引用以下类,可在“获取SDK”包中的“src”文件下查看: Constant:demo中用到的常量。 SSLCipherSuiteUtil:tls认证配置参数的工具类,比如配置客户端不校验证书。 UnsupportProtocolException:异常处理类。 public class HttpClientDemo { private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientDemo.class); public static void main(String[] args) throws Exception { // Create a new request. Request httpClientRequest = new Request(); try { // Set the request parameters. // AppKey, AppSecrect, Method and Url are required parameters. // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. // In this example, the AK/SK are stored in environment variables for identity authentication. // Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. httpClientRequest.setKey(System.getenv("HUAWEICLOUD_SDK_AK")); httpClientRequest.setSecret(System.getenv("HUAWEICLOUD_SDK_SK")); httpClientRequest.setMethod("POST"); // Set a request URL in the format of https://{Endpoint}/{URI}. httpClientRequest.setUrl("put your request url here"); httpClientRequest.addHeader("Content-Type", "text/plain"); // Set a body for http request. httpClientRequest.setBody("put your request body here"); } catch (Exception e) { LOGGER.error(e.getMessage()); return; } CloseableHttpClient client = null; try { // Sign the request. HttpRequestBase signedRequest = Client.sign(httpClientRequest, Constant.SIGNATURE_ALGORITHM_SDK_HMAC_SHA256); if (Constant.DO_VERIFY) { // creat httpClient and verify ssl certificate HostName.setUrlHostName(httpClientRequest.getHost()); client = (CloseableHttpClient) SSLCipherSuiteUtil.createHttpClientWithVerify(Constant.INTERNATIONAL_PROTOCOL); } else { // creat httpClient and do not verify ssl certificate client = (CloseableHttpClient) SSLCipherSuiteUtil.createHttpClient(Constant.INTERNATIONAL_PROTOCOL); } HttpResponse response = client.execute(signedRequest); // Print the body of the response. HttpEntity resEntity = response.getEntity(); if (resEntity != null) { LOGGER.info("Processing Body with name: {} and value: {}", System.getProperty("line.separator"), EntityUtils.toString(resEntity, "UTF-8")); } } catch (Exception e) { LOGGER.error(e.getMessage()); } finally { if (client != null) { client.close(); } } } } 运行HttpClientDemo.java,对请求进行签名、访问API并打印结果。 示例结果如下: [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Print the authorization: [Authorization: SDK-HMAC-SHA256 Access=3afe0280a6e1466e9cb6f23bcccdba29, SignedHeaders=host;x-sdk-date, Signature=26b2abfa40a4acf3c38b286cb6cbd9f07c2c22d1285bf0d4f6cf1f02d3bfdbf6] [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Print the status line of the response: HTTP/1.1 200 OK [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Date and value: Fri, 26 Aug 2022 08:58:51 GMT [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Content-Type and value: application/json [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Transfer-Encoding and value: chunked [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Connection and value: keep-alive [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Server and value: api-gateway [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: X-Request-Id and value: 10955c5346b9512d23f3fd4c1bf2d181 [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Body with name: and value: {"200": "sdk success"} 显示{"200": "sdk success"},表示签名成功,API成功请求到后端。 如果改变AK或SK的值,API网关将返回的错误信息error_msg。
  • 准备环境 获取并安装IntelliJ IDEA 2018.3.5或以上版本,可至IntelliJ IDEA官方网站下载。 获取并安装Python安装包(可使用2.7.9+或3.X,包含2.7.9),可至Python官方下载页面下载。 Python安装完成后,在命令行中使用pip安装“requests”库。 pip install requests 如果pip安装requests遇到证书错误,请下载并使用Python执行此文件,升级pip,然后再执行以上命令安装。 在IDEA中安装Python插件,如下图所示。
  • 请求签名与API调用 在命令行中,使用pip安装“requests”库。 1 pip install requests 在工程中引入apig_sdk。 1 2 from apig_sdk import signer import requests 生成一个新的Signer,填入AK和SK。 1 2 3 4 5 6 sig = signer.Signer() # Set the AK/SK to sign and authenticate the request. # Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. # In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. sig.Key = os.getenv('HUAWEICLOUD_SDK_AK') sig.Secret = os.getenv('HUAWEICLOUD_SDK_SK') 生成一个新的Request,指定域名、方法名、请求uri和body。 以虚拟私有云服务的查询VPC列表接口为例,HTTP方法为GET,域名(Endpoint)为service.region.example.com,请求URI:/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limit=1 1 2 3 # The following example shows how to set the request URL and parameters to query a VPC list. r = signer.HttpRequest("GET", "https://{service}.region.example.com/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limit=1") # r.body = "{\"a\":1}" 添加需要签名的请求消息头,或者其他用途的头域,如多项目场景中添加X-Project-Id,或者全局服务场景中添加X-Domain-Id。如果添加多个请求消息头,使用英文逗号分隔。 1 r.headers = {"X-Project-Id": "xxx"} 进行签名,执行此函数会在请求参数中添加用于签名的X-Sdk-Date头和Authorization头。 1 sig.Sign(r) X-Sdk-Date是一个必须参与签名的请求消息头参数。 您无需关注哪些消息头参数参与了签名,由SDK自行完成。 访问API,查看访问结果。 1 2 3 resp = requests.request(r.method, r.scheme + "://" + r.host + r.uri, headers=r.headers, data=r.body) print(resp.status_code, resp.reason) print(resp.content)
  • Incorrect IAM authentication information: AK access failed to reach the limit, forbidden { "error_msg": "Incorrect IAM authentication information: AK access failed to reach the limit,forbidden." ...... "error_code": "APIGW.0301", "request_id": "******" }
  • Incorrect IAM authentication information: decrypt token fail { "error_msg": "Incorrect IAM authentication information: decrypt token fail", "error_code": "APIGW.0301", "request_id": "******" } 可能原因 用户的API所属IAM认证,TOKEN解析失败。 解决办法 检查获取token的方法,token是否正确。 检查获取token的环境与调用的环境是否一致。
  • Incorrect IAM authentication information: Get secretKey failed { "error_msg": "Incorrect IAM authentication information: Get secretKey failed,ak:******,err:ak not exist", "error_code": "APIGW.0301", "request_id": "******" } 可能原因 用户的API所属IAM认证,使用AK/SK签名方式访问,但是AK不存在。 解决方法 检查AK填写是否正确。
  • Incorrect IAM authentication information: verify aksk signature fail { "error_msg": "Incorrect IAM authentication information: verify aksk signature fail, ...... "error_code": "APIGW.0301", "request_id": "******" }
  • 准备环境 获取并安装IntelliJ IDEA 2018.3.5或以上版本,可至IntelliJ IDEA官方网站下载。 获取并安装PHP安装包8.0.3或以上版本,可至PHP官方下载页面下载。 将PHP安装目录中的“php.ini-production”文件复制到“C:\windows”,改名为“php.ini”,并在文件中增加如下内容。 1 2 3 extension_dir = "{php安装目录}/ext" extension=openssl extension=curl 在IDEA中安装PHP插件,如下图所示。
  • 请求签名与API调用 在工程中引入sdk(signer.go)。 import "./core" 生成一个新的Signer,分别输入AK和SK值。 s := core.Signer{ // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. Key: os.Getenv("HUAWEICLOUD_SDK_AK"), Secret: os.Getenv("HUAWEICLOUD_SDK_SK"), } 生成一个新的Request,指定域名、方法名、请求url和body。 //The following example shows how to set the request URL and parameters to query a VPC list. //Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped. r, _ := http.NewRequest("GET", "https://service.region.example.com/v1/{project_id}/vpcs?a=1", ioutil.NopCloser(bytes.NewBuffer([]byte("")))) 添加需要签名的其他头域,或者其他用途的头域,如多项目场景中添加X-Project-Id,或者全局服务场景中添加X-Domain-Id。 /Add header parameters, for example, X-Domain-Id for invoking a global service and X-Project-Id for invoking a project-level service. r.Header.Add("X-Project-Id", "xxx") 进行签名,执行此函数会在请求中添加用于签名的X-Sdk-Date头和Authorization头。 s.Sign(r) 访问API,查看访问结果。 resp, err := http.DefaultClient.Do(r) body, err := ioutil.ReadAll(resp.Body)
  • 准备环境 获取并安装IntelliJ IDEA 2018.3.5或以上版本,可至IntelliJ IDEA官方网站下载。 获取并安装Nodejs安装包15.10.0或以上版本,可至Nodejs官方下载页面下载。 NodeJs安装后,在命令行中,用npm安装“moment”和“moment-timezone”模块。 npm install moment --save npm install moment-timezone --save 在IDEA中安装Nodejs插件,如下图所示。
  • API调用(Node.js) 在命令行中,用npm安装“moment”和“moment-timezone”模块。 1 2 npm install moment --save npm install moment-timezone --save 在工程中引入signer.js。 1 2 var signer = require('./signer') var http = require('http') 生成一个新的Signer,填入“Key”和“Secret”。 1 2 3 4 5 var sig = new signer.Signer() // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. sig.Key = process.env.HUAWEICLOUD_SDK_AK sig.Secret = process.env.HUAWEICLOUD_SDK_SK 生成一个新的Request,指定域名、方法名、请求uri和body。 1 2 3 4 5 //The following example shows how to set the request URL and parameters to query a VPC list. var r = new signer.HttpRequest("GET", "service.region.example.com/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limie=1"); //Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped. r.body = ''; 添加需要签名的其他头域,或者其他用途的头域,如多项目场景中添加X-Project-Id,或者全局服务场景中添加X-Domain-Id。 1 2 //Add header parameters, for example, X-Domain-Id for invoking a global service and X-Project-Id for invoking a project-level service. r.headers = {"X-Project-Id": "xxx"}; 进行签名,执行此函数会生成请求参数,用于创建https请求,请求参数中添加了用于签名的X-Sdk-Date头和Authorization头。 1 var opt = sig.Sign(r) 访问API,查看访问结果。 1 2 3 4 5 6 7 8 9 10 11 var req = https.request(opt, function(res){ console.log(res.statusCode) res.on("data", function(chunk){ console.log(chunk.toString()) }) }) req.on("error",function(err){ console.log(err.message) }) req.write(r.body) req.end()
  • 请求签名与API调用 在Android工程中的“app/libs”目录下,加入SDK所需jar包。其中jar包必须包括: java-sdk-core-x.x.x.jar commons-logging-1.2.jar joda-time-2.9.9.jar 在“build.gradle”文件中加入okhttp库的依赖。 在“build.gradle”文件中的“dependencies”下加入“implementation 'com.squareup.okhttp3:okhttp:3.11.0'”。 1 2 3 4 5 dependencies { ... ... implementation 'com.squareup.okhttp3:okhttp:3.11.0' } 创建request,输入AK和SK,并指定域名、方法名、请求uri和body。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Request request = new Request(); try { // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. request.setKey(System.getenv("HUAWEICLOUD_SDK_AK")); request.setSecret(System.getenv("HUAWEICLOUD_SDK_SK")); request.setMethod("GET"); request.setUrl("https://service.region.example.com3/v1/{project_id}/vpcs"); request.addQueryStringParam("name", "value"); request.addHeader("Content-Type", "text/plain"); //request.setBody("demo"); } catch (Exception e) { e.printStackTrace(); return; } 对请求进行签名,生成okhttp3.Request对象来访问API。 1 2 3 okhttp3.Request signedRequest = Client.signOkhttp(request); OkHttpClient client = new OkHttpClient.Builder().build(); Response response = client.newCall(signedRequest).execute();