Java
操作场景
使用Java语言调用APP认证的API时,您需要先获取SDK,然后导入示例代码,最后参考调用API示例调用API。
本章节以Eclipse 4.5.2版本为例介绍。
前提条件
- 已获取API调用信息,具体参见认证前准备。
- 已安装Eclipse 3.6.0或以上版本,如果未安装,请至Eclipse官方网站下载。
- 已安装IDEA 2022.2.1,如果未安装,请至IDEA官方网站下载。
- 已安装Java Development Kit 1.8.111或以上版本,如果未安装,请至Oracle官方下载页面下载。暂不支持Java Development Kit 17或以上版本。
获取SDK
请登录API网关控制台,参考《API网关用户指南》的“SDK”章节,进入SDK页面并下载SDK。
或直接下载SDK的最新版本,获取“ApiGateway-java-sdk.zip”压缩包,解压后目录结构如下:
名称 |
说明 |
---|---|
libs\java-sdk-core-x.x.x.jar |
签名SDK |
pom.xml |
构建Maven工程所需,定义其他依赖包 |
changelog |
变更日志 |
src |
验证签名SDK的demo代码:
引用类:
|
如果使用maven构建,可以使用SDK包中的libs\java-sdk-core-x.x.x.jar,x.x.x为SDK包版本号,例如3.2.4。加入java-sdk-core依赖的maven配置项为:
1 2 3 4 5 6 7 8 |
<dependency> <!-- 使用时替换为实际路径--> <systemPath>${project.basedir}/libs/java-sdk-core-XXX.jar</systemPath> <groupId>com.huawei.apigateway</groupId> <artifactId>java-sdk-core</artifactId> <version>SDK版本号</version> <scope>system</scope> </dependency> |
打包时依赖包需要下载安装到本地仓库进行打包。
使用maven构建时,settings.xml文件需要修改,增加以下内容:
- 在profiles节点中添加如下内容:
<profile> <id>MyProfile</id> <repositories> <repository> <id>HuaweiCloudSDK</id> <url>https://mirrors.huaweicloud.com/repository/maven/huaweicloudsdk/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>HuaweiCloudSDK</id> <url>https://mirrors.huaweicloud.com/repository/maven/huaweicloudsdk/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> </profile>
- 在mirrors节点中增加:
<mirror> <id>huaweicloud</id> <mirrorOf>*,!HuaweiCloudSDK</mirrorOf> <url>https://repo.huaweicloud.com/repository/maven/</url> </mirror>
- 增加activeProfiles标签激活配置:
<activeProfiles> <activeProfile>MyProfile</activeProfile> </activeProfiles>
IDEA的配置方式
支持以下几种配置方式,用户可根据业务需求选择。
- 导入示例代码
- 创建IDEA maven工程
- 打开IDEA,在菜单栏选择“File > NEW > Project”。
- 在弹窗中选择“New Project”,填写并选择以下参数后,单击“Create”。
Build system:选择“Maven”
JDK:用户自己的版本。
- IDEA支持在当前窗口或新窗口创建工程。此处,在弹窗中单击“New Window”。
- 把示例工程中的“src”和“libs”文件夹复制到apig-sdk-maven-demo工程下。
- 配置新建Maven工程的pom.xml文件。
在左侧展开工程文件,双击“pom.xml”将以下内容复制粘贴替换原有内容。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.huawei.apigateway</groupId> <artifactId>java</artifactId> <version>1.0.0</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.15</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.13</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> </dependency> <dependency> <!-- 使用时替换为实际路径--> <systemPath>${project.basedir}/libs/java-sdk-core-XXX.jar</systemPath> <groupId>com.huawei.apigateway</groupId> <artifactId>java-sdk-core</artifactId> <version>SDK版本号</version> <scope>system</scope> </dependency> <dependency> <groupId>org.openeuler</groupId> <artifactId>bgmprovider</artifactId> <version>1.0.3</version> </dependency> </dependencies> </project>
- 下载Maven依赖,选择“pom.xml”并右键选择“Maven > Reload project”。
- 在左侧工程下展开“src”文件,双击“HttpClientDemo”,如下图有绿色箭头表示创建成功。
调用API示例
- 把API信息替换到HttpClientDemo.java中对应位置。
- 本示例以AK和SK保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。以Linux系统为例在本地将已获取的AK/SK设置为环境变量。
- 把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。