Esta página ainda não está disponível no idioma selecionado. Estamos trabalhando para adicionar mais opções de idiomas. Agradecemos sua compreensão.

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
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 2024-10-10 GMT+08:00

Scenarios

To use Java to call an API through App authentication, obtain the Java SDK, create a project or import an existing project, and then call the API by referring to the API calling example.

Figure 1 API calling process

Prerequisites

  • You have obtained API calling information. For details, see Preparations.
  • You have installed the development tool and Java development environment. For details, see Preparations.

Obtaining the SDK

Old version: Log in to the ROMA Connect console, choose API Connect > API Calling > SDKs, and download the SDK.

New version: Log in to the ROMA Connect console, choose API Connect > Credentials > SDKs, and download the SDK.

The following shows the directory structure after the decompression.

Name

Description

libs\

SDK dependencies

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

SDK package

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

Sample code for signing requests

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

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

.classpath

Java project configuration files

.project

Importing a Project

  1. Start IntelliJ IDEA and choose Import Project.

    The Select File or Directory to Import dialog box is displayed.

  2. Select the directory where the SDK is decompressed and click OK.

  3. Select Eclipse for Import project from external model and click Next. Retain the default settings and click Next until the Please select project SDK page is displayed.
    Figure 2 Import Project
  4. Click Finish.
    Figure 3 Finish
  5. After the import is complete, the directory structure is shown in the following figure.
    Figure 4 Directory structure

Creating a Project

  1. Start IntelliJ IDEA and choose Create New Project.

    The New Project dialog box is displayed.

  2. In the right pane, select Java and click Next.
    Figure 5 New Project dialog box
  3. Retain the default settings and click Next. On the page displayed, set Project name and select the local directory where the project is created for Project location.
    Figure 6 New Project dialog box
  4. Import the .jar files in the Java SDK.
    1. Choose File > Project Structure. The Project Structure dialog box is displayed.
      Figure 7 Importing the .jar files
    2. In the Project Structure dialog box, choose Libraries > + > Java. The Select Library Files dialog box is displayed.
    3. Select all .jar files in \libs of the directory where the SDK is located and click OK.
      Figure 8 Selecting the .jar files
    4. Select the project created in step 3 and click OK.
      Figure 9 Selecting a project
    5. Enter the name of the directory where the JAR file is located and click Apply and OK.
      Figure 10 JAR file directory
    6. After the JAR file is imported, the directory structure is shown in the following figure.
      Figure 11 Directory structure
  5. Create a package and a class named Main.
    1. Right-click src and choose New > Package from the shortcut menu.
      Figure 12 Creating a package
    2. Enter com.apig.sdk.demo for Name.
      Figure 13 Setting a package name
    3. Click OK.
    4. Right-click com.apig.sdk.demo, choose New > Java Class from the shortcut menu, enter Main in the Name text box, and click OK.
      Figure 14 Creating a class
    5. Configure a class.
      After the class is created, open the Main file and add public static void main(String[] args) to the file.
      Figure 15 Configuring the class
  6. View the directory structure of the project.
    Figure 16 Directory structure of the new project

    Before using Main.java, enter the required code according to API Calling Example.

API Calling Example

NOTE:
  • This section demonstrates how to access a published API.
  • Before accessing an API, you must create and publish the API on the ROMA Connect console. You can specify the Mock backend for the API.
  • The backend of this API is a fake HTTP service, which returns response code 200 and message body Congratulations, sdk demo is running.
  1. Add the following references to Main.java:
    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. Create a request with the following parameters. For details about how to obtain the values, see Obtaining API Calling Information.
    • Key: key of the credential authorized by the API. Set this parameter as required.
    • Secret: secret of the credential authorized by the API. Set this parameter as required.
      NOTE:

      Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables. In this example, the AK and SK are stored in environment variables. Before running the code in this example, configure environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.

    • Method: request method. The sample code uses POST.
    • url: request URL of the API, excluding the QueryString and fragment parts. For the domain name, use your own independent domain name bound to the group to which the API belongs. The example code uses http://serviceEndpoint/java-sdk as an example.
    • QueryStringParam: query parameters carried in the URL. Characters (0-9a-zA-Z./;[]\-=~#%^&_+:") are allowed. The sample code uses name=value.
    • Header: request header. Set a request header as required. It cannot contain underscores (_). The sample code uses Content-Type:text/plain. If you are going to publish the API in a non-RELEASE environment, specify an environment name. The sample code uses x-stage:publish_env_name.
    • body: request body. The sample code uses demo.

    The sample code is as follows:

            Request request = new Request();
            try
            {
                // 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"));
                request.setMethod("POST");
                request.setUrl("http://serviceEndpoint/java-sdk");
                request.addQueryStringParam("name", "value");
                request.addHeader("Content-Type", "text/plain");
                //request.addHeader("x-stage", "publish_env_name"); //If the API is published in an environment other than RELEASE, uncomment this line and add an environment name.
                request.setBody("demo");
            } catch (Exception e)
            {
                e.printStackTrace();
                return;
            }
  3. Sign the request, access the API, and print the result.
    The sample code is as follows:
            CloseableHttpClient client = null;
            try
            {
                HttpRequestBase signedRequest = Client.sign(request);
    
    //If the subdomain name allocated by the system is used to access the API of HTTPS requests, uncomment the two lines of code to ignore the certificate verification.
                // SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
                // SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
    
    //If the subdomain name allocated by the system is used to access the API of HTTPS requests, add .setSSLSocketFactory(sslSocketFactory) to the end of custom() to ignore the certificate verification.
                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. Choose Main.java, right-click, and choose Run As > Java Application to run the project test code.
    Figure 17 Running the project test code
  5. On the Console tab page, view the running result.
    Figure 18 Response displayed if the calling is successful

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback