云服务器内容精选

  • 获取SDK 点此下载SDK与Demo。 解压后目录结构如下: 名称 说明 libs\java-sdk-core-x.x.x.jar 签名SDK pom.xml 构建Maven工程所需,定义其他依赖包 changelog 变更日志 src 验证签名SDK的demo代码: WebSocketDemo.java OkHttpDemo.java、 LargeFileUploadDemo.java HttpClientDemo.java 引用类: Constant.java SSLCipherSuiteUtil.java UnsupportProtocolException.java
  • API调用 示例代码修改调用环境信息后可直接调用。以下以新建工程为例,介绍如何在您的应用中调用SDK进行请求签名。 把API信息替换到HttpClientDemo.java中对应位置。 本示例以AK和SK保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。以Linux系统为例在本地将已获取的AK/SK设置为环境变量。 打开终端,输入以下命令打开环境变量配置文件。 vi ~/.bashrc 设置环境变量,保存文件并退出编辑器。 export HUAWEICLOUD_SDK_AK="已获取AK值" export HUAWEICLOUD_SDK_SK="已获取SK值" 输入以下命令使配置文件生效。 source ~/.bashrc 把API信息和已设置的环境变量替换到HttpClientDemo.java中对应位置。 HttpClientDemo中引用以下类,可在“获取SDK”包中的“src”文件下查看: Constant:demo中用到的常量。 SSLCipherSuiteUtil:tls认证配置参数的工具类,比如配置客户端不校验证书。 UnsupportProtocolException:异常处理类。 public class HttpClientDemo { private static final Logger LOG GER = 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=3afe***ba29, SignedHeaders=host;x-sdk-date, Signature=26b2***dbf6] [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官方网站下载。 获取并安装Nodejs安装包15.10.0或以上版本,可至Nodejs官方下载页面下载。 NodeJs安装后,在命令行中,用npm安装“moment”和“moment-timezone”模块。 npm install moment --savenpm install moment-timezone --save 在IDEA中安装Nodejs插件,如下图所示。
  • API调用(Node.js) 在命令行中,用npm安装“moment”和“moment-timezone”模块。 12 npm install moment --savenpm install moment-timezone --save 在工程中引入signer.js。 12 var signer = require('./signer')var https = require('https') 生成一个新的Signer,填入AK和SK。 本示例以AK和SK保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。以Linux系统为例在本地将已获取的AK/SK设置为环境变量。 打开终端,输入以下命令打开环境变量配置文件。 vi ~/.bashrc 设置环境变量,保存文件并退出编辑器。 export HUAWEICLOUD_SDK_AK="已获取AK值" export HUAWEICLOUD_SDK_SK="已获取SK值" 输入以下命令使配置文件生效。 source ~/.bashrc 生成一个新的Signer,填入已设置的环境变量。 12345 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_AKsig.Secret = process.env.HUAWEICLOUD_SDK_SK 生成一个新的Request,指定 域名 、方法名、请求uri和body。 12345 //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。 12 //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 91011 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()