El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Java

Updated on 2025-01-24 GMT+08:00

Scenarios

To use Java to call an API through app authentication, obtain the Java SDK, import the sample code, and then call the API by referring to the API calling example.

This section uses Eclipse 4.5.2 as an example.

Figure 1 API calling process

Prerequisites

  • You have obtained API calling information. For details, see Preparation.
  • You have installed Eclipse 3.6.0 or a later version. If not, download Eclipse from the official Eclipse website and install it.
  • You have installed IntelliJ IDEA 2022.2.1. If not, download the installation package from the official IntelliJ IDEA website and install it.
  • You have installed Java Development Kit (JDK) 1.8.111 or a later version. If not, download JDK from the official Oracle website and install it. JDK 17 or later is not supported.

Obtaining the SDK

On the APIG console, choose Help Center > Using SDKs, and download the SDK of the desired language.

Alternatively, download the latest SDK version. Then obtain the ApiGateway-java-sdk.zip package. The following table shows the files decompressed from the package.

Name

Description

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

Signing SDK

pom.xml

Required for defining dependencies when building Maven projects

changelog

Change log

src

Demo code of the signature verification SDK

  • WebSocketDemo.java
  • OkHttpDemo.java
  • LargeFileUploadDemo.java
  • HttpClientDemo.java

Classes:

  • Constant.java
  • SSLCipherSuiteUtil.java
  • UnsupportProtocolException.java

Configuring IDEA

Use any of the following configuration methods:

  1. Importing the Sample Project
    1. Start IDEA and choose File > New > Project from Existing Sources.

      Select the decompressed APIGW-java-sdk-x.x.x folder, and click OK to import the sample project.

    2. On the Import Project page, select Create project from existing sources.

      Click Next until Import Project is displayed, select Maven, and click Create.

    3. You can create a project in the current window or a new window. In this example, click New Window.
  2. Creating a Maven Project
    1. Start IDEA and choose File > New > Project.
    2. Select New Project, set the following parameters, and click Create.

      Name: Enter apig-sdk-maven-demo.

      Build System: Select Maven.

      JDK: Select the version you use.

    3. Click New Window. You can also create a project in the current window.
    4. Copy the src and libs folders in the sample project to the apig-sdk-maven-demo project.

    5. Configure the pom.xml file of the new Maven project.
      Expand the project file on the left, double-click pom.xml, and replace the file content with the following code: Download the dependency to the local repository for packaging.
      <?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> 
                 <!--Replace this with the actual path.-->      
                  <systemPath>${project.basedir}/libs/java-sdk-core-XXX.jar</systemPath>            
                  <groupId>com.huawei.apigateway</groupId>
                  
      	    <artifactId>java-sdk-core</artifactId>            
          <version>SDK package version</version>    
      	    <scope>system</scope>        
              </dependency>
              <dependency>
                  <groupId>org.openeuler</groupId>
                  <artifactId>bgmprovider</artifactId>
                  <version>1.0.3</version>
              </dependency>
          </dependencies>
      
      </project>
    6. Configure the Maven configuration file settings.xml.
      1. Add the following content to the profiles section:
        <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. Add the following content to the mirrors section:
        <mirror>
            <id>huaweicloud</id>
            <mirrorOf>*,!HuaweiCloudSDK</mirrorOf>
            <url>https://repo.huaweicloud.com/repository/maven/</url>
        </mirror>
      3. Add the activeProfiles tag to activate the configurations.
        <activeProfiles>
            <activeProfile>MyProfile</activeProfile>
        </activeProfiles>
    7. To download the Maven dependency, right-click pom.xml, and choose Maven > Reload project from the shortcut menu.

    8. Expand the src file under the project on the left and double-click HttpClientDemo. If a green arrow is displayed, the creation is successful, as shown in the following figure.

API Calling Example

  1. Replace the API information in the HttpClientDemo.java file.

    1. In this example, the AK and SK stored in the environment variables are used. Specify the environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK in the local environment first. The following uses Linux as an example to describe how to set the obtained AK/SK as environment variables.
      1. Open the terminal and run the following command to open the environment variable configuration file:

        vi ~/.bashrc

      2. Set environment variables, save the file, and exit the editor.
        export HUAWEICLOUD_SDK_AK="Obtained AK"
        export HUAWEICLOUD_SDK_SK="Obtained SK"
      3. Run the following command to apply the modification:

        source ~/.bashrc

    2. Replace the API information and configured environment variables in the HttpClientDemo.java file.
      NOTE:

      HttpClientDemo references the following classes (view them in the src file mentioned in section "Obtaining the SDK"):

      • Constant: constants used in the demo
      • SSLCipherSuiteUtil: TLS authentication configuration tool. For example, it can be used to configure skipping certificate verification on clients.
      • UnsupportProtocolException: exception handling class
      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. Run HttpClientDemo.java to sign the request, access the API, and print the result.

    The following is an example output:

    [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"}

    If {"200": "sdk success"} is displayed, the signing is successful and the API request is sent to the backend.

    If the AK or SK has changed, APIG returns an error message.

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback