Java

This section uses Eclipse as an example to describe how to integrate the Java SDK for API request signing. You can import the sample project in the code package, and integrate the signing SDK into your application by referring to the API calling example.

The signing SDK is used for signing requests and not used for cloud service access. For the cloud service SDK, see SDK Development Guide.

Preparing the Environment

  • Download the Eclipse installation file or package from the Eclipse official website, and install Eclipse or decompress the package for use.

Obtaining the SDK

Download the SDK at https://obs.cn-north-1.myhuaweicloud.com/apig-sdk/APIGW-java-sdk.zip.

The following table shows the directory structure of the package.

Name

Description

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

Signing SDK and dependencies

libs\commons-codec-x.x.jar

libs\commons-logging-x.x.jar

libs\httpclient-x.x.x.jar

libs\httpcore-x.x.x.jar

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

Sample code for signing requests

.classpath

Sample project files

.project

To build a project with Maven, download the java-sdk-core-x.x.x.jar file in the SDK from https://mirrors.huaweicloud.com/repository/maven/huaweicloudsdk/.

The following are the Maven configuration items for adding the java-sdk-core dependency:

1
2
3
4
5
<dependency>
    <groupId>com.huawei.apigateway</groupId>
    <artifactId>java-sdk-core</artifactId>
    <version>3.0.12</version>
</dependency>

If you build a project with Maven, modify the settings.xml file by adding the following content:

  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>*</mirrorOf>
        <url>https://mirrors.huaweicloud.com/repository/maven/</url>
    </mirror>
  3. Add the activeProfiles tag to activate the configurations.
    <activeProfiles>
        <activeProfile>MyProfile</activeProfile>
    </activeProfiles>

Importing the Sample Project

  1. Start Eclipse and choose File > Import. In the Import dialog box, choose General > Existing Projects into Workspace, and select the APIGW-java-sdk-x.x.x folder.

    Figure 1 Import
    Figure 2 Import Projects

  2. Click Finish. The following figure shows the imported sample project.

    Figure 3 Sample project for signing requests

If Eclipse is installed, the JDK environment has been configured. Therefore, no more descriptions about JDK environment are provided.

Creating a Project with the Signing SDK

  1. Start Eclipse and create a Java project. Specify a project name, for example, java-sdk-demo. Retain the default values for other parameters and click Finish.

  2. Import the .jar files in the Java SDK.

    1. Right-click the created project java-sdk-demo and choose Build Path > Add External Archives.

    2. Select all .jar files in the java\libs directory.

    3. Click Open.

  3. Create a package and a class named Main.

    1. Right-click src and choose New > Package.

    2. Enter com.apig.sdk.demo for Name.

    3. Click Finish.

      The package is created.

    4. Right-click com.apig.sdk.demo and choose New > Class.

    5. Enter Main for Name and select public static void main(String[] args).

    6. Click Finish.

      The Main file is created.

  4. The project is created.

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

Calling APIs

The sample project can be invoked after you change the environment information. The following is a procedure for invoking the SDK in an application to sign requests.

  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. Create a request and set required parameters.

    Sample code and annotations:
     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
    Request request = new Request();
            try {
                //Set the AK/SK to sign and authenticate the request.
                request.setKey("QTWAOYTTINDUT2QVKYUC");
                request.setSecret("MFyfvK41ba2giqM7Uio6PznpdUKGpownRZlmVmHc");
    
                //The following example shows how to set the request URL and parameters to query a VPC list.
    
                //Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH.
                request.setMethod("GET");
    
                //Set a request URL in the format of https://{Endpoint}/{URI}.
                 request.setUrl("https://{service}.region.example.com/v1/{project_id}/vpcs");
                //Set parameters for the request URL.
                request.addQueryStringParam("limit", "2");
    
                //Add header parameters, for example, X-Domain-Id for invoking a global service and X-Project-Id for invoking a project-level service.
                request.addHeader("X-Project-Id", "xxx");
    
                //Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped.
                //request.setBody("demo");
               //setBody can only be a string.
    
            } 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. Right-click Main.java and choose Run As > Java Application.

    Run the project test code.

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