Java
操作场景
使用Java语言调用APP认证的API时,您需要先获取SDK,然后导入示例代码,最后参考调用API示例调用API。
本章节以IDEA为例介绍。
前提条件
- 已安装Java Development Kit 1.8.111或以上版本,如果未安装,请至Oracle官方下载页面下载。
获取SDK
下载SDK的最新版本,获取“ApiGateway-java-sdk.zip”压缩包,解压后目录结构如下:
名称 |
说明 |
---|---|
libs\java-sdk-core-x.x.x.jar |
签名SDK |
pom.xml |
构建Maven工程所需,定义其他依赖包 |
changelog |
变更日志 |
src |
验证签名SDK的demo代码,包含WebSocketDemo.java、OkHttpDemo.java、LargeFileUploadDemo.java、HttpClientDemo.java等。 |
如果使用maven构建,可以使用SDK包中的libs\java-sdk-core-x.x.x.jar,也可以使用maven镜像仓库中的java-sdk-core-x.x.x.jar,maven仓库地址为https://mirrors.huaweicloud.com/repository/maven/huaweicloudsdk/com/huawei/apigateway/,配置maven源的方法可参见https://bbs.huaweicloud.com/forum/forum.php?mod=viewthread&tid=1779。
加入java-sdk-core依赖的maven配置项为:
1 2 3 4 5 |
<dependency> <groupId>com.huawei.apigateway</groupId> <artifactId>java-sdk-core</artifactId> <version>SDK包版本号</version> </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”。
- 在弹窗中选择“Maven Archetype”,填写并选择以下参数后,单击“Create”。
Archetype:选择“org.apache.tapestry:quickstart”。
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-3.2.0.jar</systemPath> <groupId>com.huawei.apigateway</groupId> <artifactId>java-sdk-core</artifactId> <version>3.2.0</version> <scope>system</scope> </dependency> <dependency> <groupId>org.openeuler</groupId> <artifactId>bgmprovider</artifactId> <version>1.0.3</version> </dependency> </dependencies> </project>
- 下载Maven依赖,选择“pom.xml”并右键选择“New > Maven > Reload project”。
- 在左侧工程下展开“src”文件,双击“HttpClientDemo”,如下图有绿色箭头表示创建成功。
调用API示例
- 把API信息替换到HttpClientDemo.java中对应位置。
例如,以AK/SK认证的API,API信息如下:
Ak: 3afe0280a6e1466e9cb6f23bcccdba29
Sk: ade83bfe7927407c87e1b8d7b57137c2
Host: 3560ad08298c40f3a3be3ef8c224f60f.apig.cn-north-4.huaweicloudapis.com
URL: https://3560ad08298c40f3a3be3ef8c224f60f.apig.cn-north-4.huaweicloudapis.com/apig/sdk
HttpClientDemo中引用以下类:
- 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 request = new Request(); try { // Set the request parameters. // AppKey, AppSecrect, Method and Url are required parameters. request.setKey("3afe0280a6e1466e9cb6f23bcccdba29"); request.setSecret("ade83bfe7927407c87e1b8d7b57137c2"); request.setMethod("GET"); request.setUrl("https://3560ad08298c40f3a3be3ef8c224f60f.apig.cn-north-4.huaweicloudapis.com/apig/sdk"); request.addHeader("Host", "3560ad08298c40f3a3be3ef8c224f60f.apig.cn-north-4.huaweicloudapis.com"); } catch (Exception e) { LOGGER.error(e.getMessage()); return; } CloseableHttpClient client = null; try { // Sign the request. HttpRequestBase signedRequest = Client.sign(request, Constant.SIGNATURE_ALGORITHM_SDK_HMAC_SHA256); LOGGER.info("Print the authorization: {}", Arrays.toString(signedRequest.getHeaders("Authorization"))); client = (CloseableHttpClient) SSLCipherSuiteUtil.createHttpClient(Constant.INTERNATIONAL_PROTOCOL); HttpResponse response = client.execute(signedRequest); // Print the status line of the response. LOGGER.info("Print the status line of the response: {}", response.getStatusLine().toString()); // Print the header fields of the response. Header[] resHeaders = response.getAllHeaders(); for (Header h : resHeaders) { LOGGER.info("Processing Header with name: {} and value: {}", h.getName(), h.getValue()); } // 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。