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

Java

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

准备环境

  • 获取并安装IDEA 2022.2.1,可至IDEA官方网站下载可执行文件进行安装,或者下载全量压缩包并解压后直接使用。
  • JDK:Java Development Kit 1.8.111及以上版本,可至Oracle官方下载页面下载。暂不支持Java Development Kit 17或以上版本。

获取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

IDEA的配置方式

支持以下几种配置方式,用户可根据业务需求选择。

  1. 导入示例代码
    1. 打开IDEA,在菜单栏选择“File > New > Project from Existing Sources”

      选择解压后的“APIGW-java-sdk-x.x.x”文件夹,单击“OK”,导入示例工程。

    2. 在“Import Project”页面,选择“Create project from existing sources”。

      连续单击“Next”,选择“Maven”,最后单击“Create”。

    3. IDEA支持在当前窗口或新窗口创建工程。此处,在弹窗中单击“New Window”。
  2. 创建IDEA maven工程
    1. 打开IDEA,在菜单栏选择“File > NEW > Project”。
    2. 在弹窗中选择“New Project”,填写并选择以下参数后,单击“Create”。

      Name:填写“apig-sdk-maven-demo”。

      Build system:选择“Maven”

      JDK:用户自己的版本。

    3. IDEA支持在当前窗口或新窗口创建工程。此处,在弹窗中单击“New Window”。
    4. 把示例工程中的“src”和“libs”文件夹复制到apig-sdk-maven-demo工程下。

    5. 配置新建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>
    6. 配置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>
    7. 下载Maven依赖,选择“pom.xml”并右键选择“Maven > Reload project”。

    8. 在左侧工程下展开“src”文件,双击“HttpClientDemo”,如下图有绿色箭头表示创建成功。

API调用

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

  1. 把API信息替换到HttpClientDemo.java中对应位置。

    1. 本示例以AK和SK保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。以Linux系统为例在本地将已获取的AK/SK设置为环境变量。
      1. 打开终端,输入以下命令打开环境变量配置文件。

        vi ~/.bashrc

      2. 设置环境变量,保存文件并退出编辑器。
        export HUAWEICLOUD_SDK_AK="已获取AK值" 
        export HUAWEICLOUD_SDK_SK="已获取SK值" 
      3. 输入以下命令使配置文件生效。

        source ~/.bashrc

    2. 把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();
                  }
              }
          }
      }

  2. 运行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。