
# Java签名指导
本节以IDEA工具为例，介绍如何在Java环境中集成API请求签名的SDK。您可以直接导入示例代码，然后参考调用说明部分将签名SDK集成到您的应用中。
![](https://support.huaweicloud.com/devg-apisign/public_sys-resources/note_3.0-zh-cn.png)
签名SDK只包含签名功能，不包含云服务的SDK功能，云服务SDK请参见[SDK](https://support.huaweicloud.com/devg-sdk/zh-cn_topic_0070637169.html)。
#### 准备环境
- 获取并安装IDEA 2022.2.1及以上，可至[IDEA官方网站](https://www.jetbrains.com/zh-cn/idea/)下载可执行文件进行安装，或者下载全量压缩包并解压后直接使用。

- 已安装JDK8及以上，JDK17以下版本的Java Development Kit，可至[Oracle官方下载页面](https://www.oracle.com/java/technologies/downloads/)下载。
 
#### 获取SDK
[点此下载SDK与Demo](https://obs.cn-north-1.myhuaweicloud.com/apig-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   引用类: - Constant.java  - SSLCipherSuiteUtil.java  - UnsupportProtocolException.java   |
   
#### IDEA的配置方式
支持以下几种配置方式，用户可根据业务需求选择。
- [导入示例代码]
- [创建IDEA maven工程]
1. **导入示例代码**
   1. 打开IDEA，在菜单栏选择"File \> New \> Project from Existing Sources"。 选择解压后的"APiGateway-java-sdk-*x.x.x*"文件夹，单击"OK"，导入示例工程。
      
   
   2. 在"Import Project"页面，选择"Import project from external model"。 选择"Maven"，单击"Create"。
      ![](https://support.huaweicloud.com/devg-apisign/zh-cn_image_0000001735422412.png "点击放大")
      
   
   3. IDEA支持在当前窗口或新窗口创建工程。此处，在弹窗中单击"New Window"，然后执行[3]。
    
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工程下。 ![](https://support.huaweicloud.com/devg-apisign/zh-cn_image_0000001390983525.png "点击放大")
      
   
   5. 配置新建Maven工程的pom.xml文件，然后执行[3]。
      在左侧展开工程文件，双击"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>
      ```
      
    
3. 配置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>
      ```
      
    
4. 下载Maven依赖，选择"pom.xml"并右键选择"Maven \> Reload project"。 ![](https://support.huaweicloud.com/devg-apisign/zh-cn_image_0000001735403342.png "点击放大")
   
5. 在左侧工程下展开"src"文件，双击"HttpClientDemo"，如下图有绿色箭头表示创建成功。 ![](https://support.huaweicloud.com/devg-apisign/zh-cn_image_0000001390985933.png "点击放大")
   
 
#### API调用
示例代码修改调用信息后可直接调用，调用信息请参考[API签名准备工作](https://support.huaweicloud.com/devg-apisign/api-sign-provide.html)章节获取。以下以新建工程为例，介绍如何在您的应用中调用SDK进行请求签名。
1. 把API信息替换到HttpClientDemo.java中对应位置。 
   1. 本示例以AK和SK保存在环境变量中为例，运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。以Linux系统为例在本地将已[获取的AK/SK](https://support.huaweicloud.com/devg-apisign/api-sign-provide-aksk.html)设置为环境变量。
      1. 打开终端，输入以下命令打开环境变量配置文件。 **vi \~/.bashrc**
         
      
      2. 设置环境变量，保存文件并退出编辑器。
         ```
         export HUAWEICLOUD_SDK_AK="已获取AK值" 
         export HUAWEICLOUD_SDK_SK="已获取SK值"
         ```
         
      
      3. 输入以下命令使配置文件生效。 **source \~/.bashrc**
         
       
   
   2. 把API信息和已设置的环境变量替换到HttpClientDemo.java中对应位置。
      ![](https://support.huaweicloud.com/devg-apisign/public_sys-resources/note_3.0-zh-cn.png)
      HttpClientDemo中引用以下类，可在"获取SDK"包中的"src"文件下查看：
      - Constant：SDK包中使用的常量类。
      
      - 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, AppSecret, 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=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。
   
   
 
