Updated on 2023-04-23 GMT+08:00

Java

Scenarios

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

This section uses IntelliJ IDEA 2018.3.5 as an example.

Figure 1 API calling process

Prerequisites

  • You have obtained the domain name, request URL, and request method of the API as well as the key and secret (or AppKey and AppSecret of the client) of the integration application. For details, see Preparations.
  • You have installed IntelliJ IDEA 2018.3.5 or later. Otherwise, download one from the IntelliJ IDEA official website and install it.
  • You have installed Java Development Kit (JDK) 1.8.111 or a later version. Otherwise, download one from the Oracle official website and install it.

Obtaining the SDK

Log in to the ROMA Connect console, choose API Connect > API Calling, and download the SDK. The directory structure after the decompression is as follows:

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

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

     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 Preparations. The sample code uses 4f5f626b-073f-402f-a1e0-e52171c6100c.
    • AppSecret: Obtain it by referring to Preparations. 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. The example code uses http://serviceEndpoint/java-sdk as an example.
    • 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. 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
            Request request = new Request();
            try
            {
                request.setKey("4f5f626b-073f-402f-a1e0-e52171c6100c"); //Obtain the value when creating an integration application.
                request.setSecret("*****"); //Obtained when an integration application is created.
                request.setMethod("POST");
                request.setUrl("http://serviceEndpoint/java-sdk");
                 //Obtain the URL when creating an API group.
                //The subdomain name is obtained when the API group is created.
                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
    36
    37
    38
    39
    40
    41
            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