更新时间:2024-02-18 GMT+08:00

Java

本节以Eclipse工具为例,介绍如何在Java环境中集成API请求签名的SDK。您可以直接导入代码包中的示例工程体验,然后参考调用说明部分将签名SDK集成到您的应用中。

准备环境

  • 获取并安装Eclipse,可至Eclipse官方网站下载可执行文件进行安装,或者下载全量压缩包并解压后直接使用。

获取SDK

点此下载SDK与Demo

解压后目录结构如下:

名称

说明

libs\java-sdk-core-x.x.x.jar

签名SDK以及依赖包

libs\commons-codec-x.x.jar

libs\commons-logging-x.x.jar

libs\httpclient-x.x.x.jar

libs\httpcore-x.x.x.jar

src\com\apig\sdk\demo\Main.java

签名请求示例代码

.classpath

签名示例工程文件

.project

加入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文件需要修改,增加以下内容:

  1. 在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>
  2. 在mirrors节点中增加:
    <mirror>
        <id>huaweicloud</id>
        <mirrorOf>*,!HuaweiCloudSDK</mirrorOf>
        <url>https://repo.huaweicloud.com/repository/maven/</url>
    </mirror>
  3. 增加activeProfiles标签激活配置:
    <activeProfiles>
        <activeProfile>MyProfile</activeProfile>
    </activeProfiles>

Eclipse的配置方式

导入示例工程

  1. 打开Eclipse,在菜单栏选择“File > Import”,弹出“Import”对话框,选择“General > Existing Projects into Workspace”,选择解压后的“APIGW-java-sdk-x.x.x”文件夹。

    图1 Import
    图2 Import Projects

  1. 单击“Finish”,完成导入。导入后的示例工程如下所示。

    图3 签名示例工程

安装了Eclipse,JDK环境一般已经配置好,这里不再说明。

新建工程并引入签名SDK

  1. 打开Eclipse,新建一个Java Project,自定义“Project name”,以“java-sdk-demo”为例。其他参数保持默认,单击“Finish”。

  2. 导入Java SDK的“jar”包。

    1. 右键单击新建的工程“java-sdk-demo”,选择“Build Path > Add External Archives”。

    2. 选择SDK中“java\libs”目录下所有以“jar”结尾的文件。

    3. 单击“打开”,完成SDK引入。

  3. 新建“Package”及“Main”文件。

    1. 右键单击“src”,选择“New > Package”。

    2. 在“Name”中输入“com.apig.sdk.demo”。

    3. 单击“Finish”。

      完成“Package”的创建。

    4. 右键单击“com.apig.sdk.demo”,选择“New > Class”。

    5. 在“Name”中输入“Main”,勾选“public static void main(String[] args)”。

    6. 单击“Finish”。

      完成“Main”文件的创建。

  4. 完成工程创建。

    “Main.java”无法直接使用,请根据实际情况参考API调用输入所需代码。

API调用

示例工程修改调用环境信息后可直接调用。以下以新建工程为例,介绍如何在您的应用中调用SDK进行请求签名。

  1. 在Main.java中加入以下引用。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    import java.io.IOException;
    import javax.net.ssl.SSLContext;
    
    import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpRequestBase;
    import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLContexts;
    import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
    import org.apache.http.impl.client.CloseableHttpClient; 
    import org.apache.http.impl.client.HttpClients; 
    import org.apache.http.util.EntityUtils; 
    
    import com.cloud.apigateway.sdk.utils.Client; 
    import com.cloud.apigateway.sdk.utils.Request;
    

  2. 创建request,填写请求以及签名所需的相关参数:

    样例代码和说明如下:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    Request request = new Request();
            try {
                //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.
    
                request.setKey(System.getenv("HUAWEICLOUD_SDK_AK")); 
                request.setSecret(System.getenv("HUAWEICLOUD_SDK_SK"));
    
                //The following example shows how to set the request URL and parameters to query a VPC list.
    
                //Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH.
                request.setMethod("GET");
    
                //Set a request URL in the format of https://{Endpoint}/{URI}.
                request.setUrl("https://endpoint.example.com/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limit=2");
    
                //Set parameters for the request URL.
                request.addQueryStringParam("limit", "2");
    
                //Add header parameters, for example, Content-Type application/json.
                request.addHeader("Content-Type", "application/json");
    
    
                //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.
                //request.setBody("demo");
               //setBody只支持string类型
    
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
    

  3. 对请求进行签名、访问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
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
            CloseableHttpClient client = null;
            try
            {
                HttpRequestBase signedRequest = Client.sign(request);
    
                client = HttpClients.custom().build();
                HttpResponse response = client.execute(signedRequest);
                System.out.println(response.getStatusLine().toString());
                Header[] resHeaders = response.getAllHeaders();
                for (Header h : resHeaders)
                {
                    System.out.println(h.getName() + ":" + h.getValue());
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null)
                {
                    System.out.println(System.getProperty("line.separator") + EntityUtils.toString(resEntity, "UTF-8"));
                }
    
            } catch (Exception e)
            {
                e.printStackTrace();
            } finally
            {
                try
                {
                    if (client != null)
                    {
                        client.close();
                    }
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
    

  4. 右键单击“Main.java”,选择“Run As > Java Application”。

    运行工程测试代码。

  5. 在“Console”页签,查看运行结果。