Updated on 2024-04-02 GMT+08:00

Java

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.

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

Log in to the APIG console, and download the SDK on the SDKs page by referring to section "SDKs" in the API Gateway User Guide. Version 3.1.2 is recommended.

Then obtain the ApiGateway-java-sdk.zip package. The following table shows the files decompressed from the package.

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. Open Eclipse and choose File > Import.

    The Import dialog box is displayed.

  2. Choose General > Existing Projects into Workspace and click Next.

    The Import Projects dialog box is displayed.

    Figure 2 Importing a project

  3. Click Browse and select the directory where the SDK is decompressed.

    Figure 3 Selecting the demo project

  4. Click Finish.

    Modify the parameters in sample code Main.java as required. For details about the sample code, see API Calling Example.

Creating a Project

  1. Open Eclipse and choose File > New > Java Project.

    The New Java Project dialog box is displayed.

  2. Enter a project name, for example, java-sdk-demo, retain the default settings for other parameters, and click Finish.

    Figure 4 Creating a project

  3. Import the .jar files in the APIG Java SDK.

    1. Choose java-sdk-demo, right-click, and choose Build Path > Add External Archives from the shortcut menu.
      Figure 5 Importing the .jar files
    2. Select all .jar files in the \libs directory.
      Figure 6 Selecting all .jar files

  4. Create a package and Main file.

    1. Choose src, right-click, and choose New > Package from the shortcut menu.
      Figure 7 Creating a package
    2. Enter com.apig.sdk.demo for Name.
      Figure 8 Setting a package name
    3. Click Finish.

      The package is created.

    4. Choose com.apig.sdk.demo, right-click, and choose New > Class from the shortcut menu.
      Figure 9 Creating a class
    5. Enter Main for Name and select public static void main(String[] args).
      Figure 10 Configuring the class
    6. Click Finish.

      The Main file is created.

  5. View the directory structure of the project.

    Figure 11 Directory structure of the new project Main

    Before using Main.java, enter the required code according to the API calling example provided in this section.

API Calling Example

  • You need to create an API with the Mock backend on the console, and then publish the API. For details about how to create and publish an API, see the API Gateway User Guide.
  • 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:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    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. Construct a request by configuring the following parameters:

    • AppKey: Obtain it by referring to Preparation. The sample code uses 4f5f****100c.
    • AppSecret: Obtain it by referring to Preparation. The sample code uses ******.
    • Method: Specify a request method. The sample code uses POST.
    • url: Request URL of the API, excluding the QueryString and fragment parts. Use your own independent domain name. The sample code uses http://c967a237-cd6c-470e-906f-a8655461897e.apigw.cn-north-1.huaweicloud.com/java-sdk.
    • queryString: Specify query parameters to be carried in the URL. Characters (0-9a-zA-Z./;[]\-=~#%^&_+:") are allowed. The sample code uses name=value.
    • header: Specify request headers. 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: Specify the request body. The sample code uses demo.

    The sample code is as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
            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("HUAWEI CLOUD_SDK_AK")); // Obtained when an app is created.
                request.setSecret(System.getenv("HUAWEI CLOUD_SDK_SK")); // Obtained when an app is created.
                request.setMethod("POST");
                request.setUrl("http://c967a237-cd6c-470e-906f-a8655461897e.apigw.exampleRegion.com/java-sdk");
                 //URL
                request.addQueryStringParam("name", "value");
                request.addHeader("Content-Type", "text/plain");
                //request.addHeader("x-stage", "publish_env_name"); //Specify an environment name before publishing the API in a non-RELEASE environment.
                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:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
            CloseableHttpClient client = null;
            try
            {
                HttpRequestBase signedRequest = Client.sign(request);
    
                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 12 Running the project test code

  5. On the Console tab page, view the running result.

    Figure 13 Response displayed if the calling is successful