Updated on 2023-01-17 GMT+08:00

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.

Preparing the Environment

  • Download the Eclipse installation file or package, and install the tool or decompress the package.

Obtaining the SDK

Log in to the API Gateway console and choose Help Center > SDK Process Flow. Then download the SDK. For details, see section "SDKs" in the User Guide.

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

Configuring Eclipse

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

  1. 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
    28
    29
    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://endpoint.example.com/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limit=2");
    
                //Set parameters for the request URL.
                request.addQueryStringParam("limit", "2");
    
                //Add header parameters, for example, Content-Type application/json.
                request.addHeader("Content-Type", "application/json");
    
    
                //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.