更新时间:2025-02-25 gmt 08:00

java-九游平台

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

签名sdk只包含签名功能,不包含云服务的sdk功能,云服务sdk请参见。

准备环境

  • 获取并安装idea 2022.2.1,可至下载可执行文件进行安装,或者下载全量压缩包并解压后直接使用。
  • jdk:java development kit 1.8.111及以上版本,可至下载。暂不支持java development kit 17或以上版本。

获取sdk

解压后目录结构如下:

名称

说明

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”将以下内容复制粘贴替换原有内容。打包时依赖包需要下载安装到本地仓库进行打包
      
      
          4.0.0
          com.huawei.apigateway
          
          java
          1.0.0
          
              
                  
                      org.apache.maven.plugins
                      maven-compiler-plugin
                      3.8.0
                      
                          1.8
                          1.8
                          utf-8
                      
                  
              
          
          
              utf-8
              1.8
              1.8
          
          
              
                  commons-codec
                  commons-codec
                  1.15
              
              
                  commons-logging
                  commons-logging
                  1.2
              
              
                  org.apache.httpcomponents
                  httpclient
                  4.5.13
              
              
                  com.squareup.okhttp3
                  okhttp
                  4.9.1
              
              
                  org.apache.httpcomponents
                  httpcore
                  4.4.13
              
              
                  org.slf4j
                  slf4j-api
                  1.7.25
                  compile
              
              
                  org.slf4j
                  slf4j-simple
                  1.7.25
              
               
                             
                  ${project.basedir}/libs/java-sdk-core-xxx.jar            
                  com.huawei.apigateway
                  
      	    java-sdk-core            
      	    sdk版本号            
      	    system        
              
              
                  org.openeuler
                  bgmprovider
                  1.0.3
              
          
      
    6. 配置maven的配置settings.xml。
      1. 在profiles节点中添加如下内容:
        
            myprofile
            
                
                    huaweicloudsdk
                    https://mirrors.huaweicloud.com/repository/maven/huaweicloudsdk/
                    
                        true
                    
                    
                        false
                    
                
            
            
                
                    huaweicloudsdk
                    https://mirrors.huaweicloud.com/repository/maven/huaweicloudsdk/
                    
                        true
                    
                    
                        false
                    
                
            
        
      2. 在mirrors节点中增加:
        
            huaweicloud
            *,!huaweicloudsdk
            https://repo.huaweicloud.com/repository/maven/
        
      3. 增加activeprofiles标签激活配置:
        
            myprofile
        
    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系统为例在本地将已设置为环境变量。
      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: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, 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.set;
                  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。

相关文档

网站地图