Updated on 2023-05-24 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 the domain name, ID, request URL, and request method of the API to be called, and the AppKey and AppSecret of the App for calling the API. For more information, 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.

Obtaining the SDK

  1. Log in to the DataArts Studio console.
  2. Click DataArts DataService.
  3. In the navigation pane, choose DataArts DataService Exclusive > SDKs.
  4. On the SDKs page, download the SDK package.
  5. Verify integrity of the SDK package. In Windows, open the CLI and run the following command to generate the SHA-256 value of the downloaded SDK package. In the command, D:\java-sdk.zip is an example local path and name of the SDK package. Replace it with the actual value.

    certutil -hashfile D:\java-sdk.zip SHA256

    The following is an example command output:

    SHA-256 hash value of D:\java-sdk.zip
    a7c0195ebf297f29ab0065da16d7e84f14911de177e6e0c8dbadf3464d12b75f
    CertUtil: -hashfile command executed.

    Compare the SHA-256 value of the downloaded SDK package with that provided in the following table. If they are the same, no tampering or packet loss occurred during the package download.

    Language

    SHA-256 Value of the SDK Package

    Java

    a7c0195ebf297f29ab0065da16d7e84f14911de177e6e0c8dbadf3464d12b75f

    Go

    caf22350181a4ecd49dc0d3f56097b10c1794792adae407140950be4ed9b6771

    Python

    c80b9ef282fc88d3fb16db4cb9d7525d3db71f7989782ed0b636920ea2fadb93

    C#

    b0e69ef60a561c54c1b86c3447ca855088a1fa2a672fbfba618aaf56b2841e8a

    JavaScript

    c64e595651de079766e446ce2c3262013256f81683bb9434bee27bed3a4caf01

    PHP

    e2eba2cae72aea794edb4057ed8eb7cb82f0dbaccabf9c5539694a7a7a9f3c89

    C++

    c173f59d816aba53f47750cf5ffdc65cc345b1613974b3d2a545ace48787f577

    C

    e4f22beb7b132fe6e57c9de79f596c3ff830228cd7221b02ca96198e501c642c

    Android

    d6c3032801ac88cf8cbc51f64d42457174447c8d159f34a187c036913b31ea2b

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.

    The following figure shows the directory structure of the project.

    Figure 4 Directory structure of the imported project

    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 5 Creating a project

  3. Import the .jar files in the API Gateway Java SDK.

    1. Choose java-sdk-demo, right-click, and choose Build Path > Add External Archives from the shortcut menu.
      Figure 6 Importing the .jar files
    2. Select all .jar files in the \libs directory.
      Figure 7 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 8 Creating a package
    2. Enter com.apig.sdk.demo for Name.
      Figure 9 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 10 Creating a class
    5. Enter Main for Name and select public static void main(String[] args).
      Figure 11 Configuring the class
    6. Click Finish.

      The Main file is created.

  5. View the directory structure of the project.

    Figure 12 Directory structure of the new project

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

API Calling Example

  • This section demonstrates how to access a published API.
  • You need to create and release an API on the DataArts DataService management console. For details about how to create and publish APIs, see DataArts Studio 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:

    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 4f5f626b-073f-402f-a1e0-e52171c6100c.
    • AppSecret: Obtain it by referring to Preparation. Set this parameter based on the site requirements. The example code uses ****** as an example.
    • Method: Specify a 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. Use the sample code in http://{apig-endpoint}/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: Request header. Set a request header as required. It cannot contain underscores (_). The sample code uses Content-Type:text/plain.
    • body: Specify the request body. The sample code uses demo.

    The sample code is as follows:

            Request request = new Request();
            try
            {
                request.setKey("4f5f626b-073f-402f-a1e0-e52171c6100c"); //Obtain the value when creating an app.
                request.setSecret("*****"); //Obtained when an app is created.
                request.setMethod("POST");
                request.setUrl("http://{apig-endpoint}/java-sdk");
                 //Obtain the URL when creating an API group.
                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, add header x-Authorization, access the API, and print the result.

    The sample code is as follows:
            CloseableHttpClient client = null;
            try
            {
                HttpRequestBase signedRequest = Client.sign(request);
                Header[] authorization = signedRequest.getHeaders("Authorization");
                signedRequest.addHeader("x-Authorization",authorization[0].getValue());
    
                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 13 Running the project test code

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

    Figure 14 Response displayed if the calling is successful