云服务器内容精选

  • 准备环境 已获取API的域名、请求url、请求方法、AppKey和AppSecret等信息,具体参见认证前准备。 获取并安装Python安装包(可使用2.7.9+或3.X),如果未安装,请至Python官方下载页面下载。 Python安装完成后,在命令行中使用pip安装“requests”库。 pip install requests 如果pip安装requests遇到证书错误,请下载并使用Python执行此文件,升级pip,然后再执行以上命令安装。 获取并安装IntelliJ IDEA,如果未安装,请至IntelliJ IDEA官方网站下载。 已在IntelliJ IDEA中安装Python插件,如果未安装,请按照图1所示安装。 图1 安装Python插件
  • 调用API示例 在工程中引入apig_sdk。 1 2 3 from apig_sdk import signer import requests import os 生成一个新的Signer,填入AppKey和AppSecret。 1 2 3 4 5 6 7 8 # 认证用的ak和sk编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全; # 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量SDK_AK和SDK_SK。 ak = os.environ("SDK_AK"); sk = os.environ("SDK_SK"); sig = signer.Signer() sig.Key = ak sig.Secret = sk 生成一个Request对象,指定方法名、请求uri、header和body。 1 2 3 4 r = signer.HttpRequest("POST", "https://c967a237-cd6c-470e-906f-a8655461897e.apigw.cn-north-1.huaweicloud.com/app1?a=1", {"x-stage": "RELEASE", "name": "value"}, "body") 进行签名,执行此函数会在请求参数中添加用于签名的X-Sdk-Date头和Authorization头。然后为请求添加x-Authorization头,值与Authorization头相同。 1 2 sig.Sign(r) r.headers["x-Authorization"] = r.headers["Authorization"] 访问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)
  • 调用API示例 把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。
  • 调用API(Node.js)示例 在工程中引入signer.js。 var signer = require('./signer') var http = require('http') 生成一个新的Signer,填入AppKey和AppSecret。 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。 var r = new signer.HttpRequest("POST", "c967a237-cd6c-470e-906f-a8655461897e.apigw.exampleRegion.com/app1?a=1"); r.body = '{"a":1}' 给请求添加x-stage头,内容为环境名。如有需要,添加需要签名的其他头域。 r.headers = { "x-stage":"RELEASE" } 进行签名,执行此函数会生成请求参数,用于创建http(s)请求,请求参数中添加了用于签名的X-Sdk-Date头和Authorization头。 var opts = sig.Sign(r) 访问API,查看访问结果。如果使用https访问,则将“http.request”改为“https.request”。 var req=http.request(opts, 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()
  • 获取SDK 请登录API网关控制台,参考《API网关用户指南》的“SDK”章节,进入SDK页面并下载SDK。 或直接下载SDK的最新版本,获取“ApiGateway-javascript-sdk.zip”压缩包,解压后目录结构如下: 名称 说明 signer.js SDK代码 node_demo.js Nodejs示例代码 demo.html 浏览器示例代码 demo_require.html 浏览器示例代码(使用require加载) test.js 测试用例 js\hmac-sha256.js 依赖库 licenses\license-crypto-js 第三方库license文件 licenses\license-node
  • 前提条件 已获取API的调用信息,具体参见认证前准备。 已安装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 已在IntelliJ IDEA中安装PHP插件,如果未安装,请按照图1所示安装。 图1 安装PHP插件
  • 调用API示例 在Android工程中的“app/libs”目录下,加入SDK所需jar包。其中jar包必须包括: java-sdk-core-x.x.x.jar joda-time-2.10.jar 在“build.gradle”文件中加入okhttp库的依赖。 在“build.gradle”文件中的“dependencies”下加入“implementation 'com.squareup.okhttp3:okhttp:3.14.2'”。 dependencies { ... ... implementation 'com.squareup.okhttp3:okhttp:3.14.3'} 创建request,输入AppKey和AppSecret,并指定域名、方法名、请求uri和body。 Request request = new Request();try {request.setKey("4f5f626b-073f-402f-a1e0-e52171c6100c");request.setSecrect("******");request.setMethod("POST");request.setUrl("https://c967a237-cd6c-470e-906f-a8655461897e.apigw.exampleRegion.com/app1");request.addQueryStringParam("name", "value");request.addHeader("Content-Type", "text/plain");request.setBody("demo");} catch (Exception e) {e.printStackTrace();return;} 对请求进行签名,生成okhttp3.Request对象来访问API。 okhttp3.Request signedRequest = Client.signOkhttp(request);OkHttpClient client = new OkHttpClient.Builder().build();Response response = client.newCall(signedRequest).execute();