All Products
Search
Document Center

Alibaba Cloud SDK:Integrate Alibaba Cloud SDK V2.0 for Java

最終更新日:Aug 20, 2024

The process of integrating Alibaba Cloud SDK V2.0 consists of three steps: configure a credential, import the SDK to your project, and write the code for calling API operations. This topic describes how to integrate Alibaba Cloud SDK V2.0. In this example, Alibaba Cloud SDK V2.0 for Java is used to call the SendSms operation of Short Message Service (SMS) to send a text message.

Prerequisites

Java Development Kit (JDK) 1.8 or later is installed.

Step 1: Configure a credential

An AccessKey pair is required if you use Alibaba Cloud SDK V2.0 to call API operations. For more information, see Credential. To prevent AccessKey pair leaks, you can record the AccessKey pair in environment variables. For information about other security solutions, see Credential security solutions. In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.

  • Linux and macOS

    Important

    The temporary environment variables that are configured by using the export command are valid only for the current session. If the session exits, the environment variables become invalid.

    1. Configure the AccessKey ID and press Enter.

      # Replace <ACCESS_KEY_ID> with your AccessKey ID. 
      export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
    2. Configure the AccessKey secret and press Enter.

      # Replace <ACCESS_KEY_SECRET> with your AccessKey secret. 
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>
    3. Check whether the configuration is successful.

      Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If the valid AccessKey ID is returned, the environment variables are configured.

  • Windows

    In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.

    Use GUI

    • Procedure

      If you want to use GUI to configure environment variables in Windows 10, perform the following steps:

      On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section. Then, configure the variables described in the following table.

      Variable

      Example

      AccessKey ID

      • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

      • Variable value: LTAI4GDty8ab9W4Y1D****

      AccessKey Secret

      • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

      • Variable value: IrVTNZNy5yQelTETg0cZML3TQn****

    • Check whether the configuration is successful.

      On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

    Use CMD

    • Procedure

      Open a Command Prompt window as an administrator and run the following commands to add environment variables in the operating system:

      setx ALIBABA_CLOUD_ACCESS_KEY_ID LTAI4GDty8ab9W4Y1D**** /M
      setx ALIBABA_CLOUD_ACCESS_KEY_SECRET IrVTNZNy5yQelTETg0cZML3TQn**** /M

      /M indicates that the environment variable is of system level. You cannot use this parameter when you configure a user-level environment variable.

    • Check whether the configuration is successful.

      On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

    Use Windows PowerShell

    In PowerShell, configure new environment variables. The environment variables apply to all new sessions.

    [System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::User)
    [System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::User)

    Configure environment variables for all users. You must run the following commands as an administrator.

    [System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'LTAI4GDty8ab9W4Y1D****', [System.EnvironmentVariableTarget]::Machine)
    [System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'IrVTNZNy5yQelTETg0cZML3TQn****', [System.EnvironmentVariableTarget]::Machine)

    Configure temporary environment variables. The environment variables are valid only for the current session.

    $env:ALIBABA_CLOUD_ACCESS_KEY_ID = "LTAI4GDty8ab9W4Y1D****"
    $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "IrVTNZNy5yQelTETg0cZML3TQn****"

    In PowerShell, run the Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_ID and Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_SECRET commands. If the valid AccessKey pair is returned, the configuration is successful.

Step 2: Import the SDK to your project

Alibaba Cloud SDK V2.0 allows you to make generic and specialized calls. For more information, see Generic calls and specialized calls. The SDK that you need to import varies based on the call type.

Make a specialized call

You can visit OpenAPI Explorer, find the service that you want to use, and view the supported languages and installation methods. Then, import the SDK of the service to your project. In this example, SMS SDK is imported. Perform the following steps:

  1. Visit the SMS SDK page.

  2. In the All languages section, select the language that you want to use.

  3. In the Installation Method section, select an installation method and copy the installation code.

  4. Add the dependency to your project.

Add the following Maven dependency to your Java project:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>dysmsapi20170525</artifactId>
  <version>2.0.24</version>
</dependency>

Make a generic call

You do not need to install the SDK of a service to make generic calls. You need to only import the com.aliyun.tea-openapi core package. For information about the latest version of the core package, see tea-openapi. Add the following dependency to your Java project:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea-openapi</artifactId>
      <version>0.2.8</version>
    </dependency>

Step 3: Call an API operation

Download the sample code. For more information, see Get started with Alibaba Cloud Darabonba SDK for Java. In this example, the sample code of a specialized call is used. If you want to make a generic call, turn on Common Request when you download the sample code. For more information, see Generic calls and specialized calls.

Initialize a request client

Method 1: Use an AccessKey pair

import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;

public class Sample {
    public static void createClient() throws Exception {
        Config config = new Config()
                Required. Specify your AccessKey ID.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Specify your AccessKey secret.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Specify the endpoint. For more information, visit https://api.aliyun.com/product/Dysmsapi.
        config.endpoint = "dysmsapi.aliyuncs.com";
        // Initialize a request client for a specialized call.
        Client dysmsapiClient = new Client(config);
    }
}

Method 2: Use an STS token

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;

public class Sample {
    public static void createClient() throws Exception {
        Config config = new Config()
                Required. Specify your AccessKey ID.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Specify your AccessKey secret.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // Required. Specify your Security Token Service (STS) token.
                .setSecurityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN"));
        // Specify the endpoint. For more information, visit https://api.aliyun.com/product/Dysmsapi.
        config.endpoint = "dysmsapi.aliyuncs.com";
        // Initialize a request client for a specialized call.
        Client dysmsapiClient = new Client(config);
    }
}

Method 3: Use the Credentials tool

The Alibaba Cloud Credentials tool provides multiple methods to initialize a Credentials client. In this example, the default credential provider chain is used. You can also select a method to initialize a Credentials client based on your business requirements. For more information, see Manage access credentials.

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;

public class Sample {
    public static void createClient() throws Exception {
        // Use the default credential to initialize a Credentials client. 
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        Config config = new Config();
        // Use the SDK Credentials package to configure a credential. 
        config.setCredential(credentialClient);
        // To call the SMS API, initialize the Client class of the SDK package for SMS.
        config.endpoint = "dysmsapi.aliyuncs.com";
        // Initialize a request client for a specialized call.
        Client dysmsapiClient = new Client(config);
    }
}

Create a request object or a runtime configuration object

In most cases, you can create a request object and specify the parameters based on your business requirements. You can also customize runtime configurations.

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    public static void createClient() throws Exception {
        // In this example, the code for initializing a Credentials client is omitted. For more information, see the preceding section.
        // Create a request object and configure the parameters.
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers("<YOUR_VALUE>")
                .setSignName("<YOUR_VALUE>");
        // Create a runtime configuration object.
        RuntimeOptions runtime = new RuntimeOptions();
    }
}

Initiate a request

In the Alibaba Cloud SDK V2.0, the client of each Alibaba Cloud service provides three request methods for all API operations of the service. You can specify a request method for an API operation. The name of the request method is the name of the API operation with the first letter in lowercase. The following list describes the request methods:

  • <API operation name>: uses the default runtime configurations to initiate a request. You do not need to specify runtime parameters.

    import com.aliyun.dysmsapi20170525.Client;
    import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
    import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
    import com.aliyun.teaopenapi.models.Config;
    import com.google.gson.Gson;
    
    public class Sample {
        public static void main(String[] args) throws Exception {
            // Use the Credentials tool to initialize a Credentials client.
            com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
            
            Config smsConfig = new Config();
            smsConfig.setCredential(credentialClient);
            smsConfig.setEndpoint("dysmsapi.aliyuncs.com");
            Client smsClient = new Client(smsConfig);
            // Construct the request object.
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            // Obtain the response object.
            SendSmsResponse sendSmsResponse = smsClient.sendSms(sendSmsRequest);
            // The response, which contains the body and headers that are returned by the server.
            System.out.println(new Gson().toJson(sendSmsResponse.body));
            System.out.println(new Gson().toJson(sendSmsResponse.headers));
        }
    }
  • <API operation name>WithOptions: uses the custom runtime configurations to initiate a request. For more information, see Advanced configuration.

    import com.aliyun.dysmsapi20170525.Client;
    import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
    import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
    import com.aliyun.teaopenapi.models.Config;
    import com.aliyun.teautil.models.RuntimeOptions;
    import com.google.gson.Gson;
    
    public class Sample {
        public static void main(String[] args) throws Exception {
            // Use the Credentials tool to initialize a Credentials client.
            com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
    
            Config smsConfig = new Config();
            smsConfig.setCredential(credentialClient);
            smsConfig.setEndpoint("dysmsapi.aliyuncs.com");
            Client smsClient = new Client(smsConfig);
            // Construct the runtime parameter object.
            RuntimeOptions runtime = new RuntimeOptions();
            // Set the timeout period for read requests.
            runtime.readTimeout=10000;
            // Set the timeout period for connection requests.
            runtime.connectTimeout=5000;
            // Specify whether to automatically retry a request.
            runtime.autoretry=false;
            // Construct the request object.
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            // Specify the runtime parameters in the request for the current call.
            SendSmsResponse sendSmsResponse = smsClient.sendSmsWithOptions(sendSmsRequest,runtime);
            // The response, which contains the body and headers that are returned by the server.
            System.out.println(new Gson().toJson(sendSmsResponse.body));
            System.out.println(new Gson().toJson(sendSmsResponse.headers));
        }
    }
  • <API operation name>Advance: used for API operations that require file uploading. By default, you must specify runtime parameters. The following sample code provides an example on how to initiate a request to upload a file and call an API operation to use the human face and body recognition feature of Visual Intelligence API (VIAPI):

    <!--    The dependency for the human face and body recognition feature of VIAPI.-->
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>facebody20191230</artifactId>
          <version>3.0.7</version>
        </dependency>
    import com.aliyun.facebody20191230.Client;
    import com.aliyun.facebody20191230.models.DetectBodyCountAdvanceRequest;
    import com.aliyun.facebody20191230.models.DetectBodyCountResponse;
    import com.aliyun.teaopenapi.models.Config;
    import com.aliyun.teautil.models.RuntimeOptions;
    import com.google.gson.Gson;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    
    public class Sample {
        public static void main(String[] args) throws Exception {
            // Use the Credentials tool to initialize a Credentials client.
            com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
            Config facebodyConfig = new Config();
            facebodyConfig.setCredential(credentialClient);
            facebodyConfig.setEndpoint("facebody.cn-shanghai.aliyuncs.com");
            Client facebodyClient = new Client(facebodyConfig);
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            // Read the file and instantiate the file stream.
            File f = new File("<YOUR-FILE-PATH>");
            InputStream in = new FileInputStream(f);
    
            DetectBodyCountAdvanceRequest request = new DetectBodyCountAdvanceRequest();
            // Configure the file stream for the SDK request object.
            request.setImageURLObject(in);
            // Upload the file by using the method for uploading local files.
            DetectBodyCountResponse resp = facebodyClient.detectBodyCountAdvance(request, runtimeOptions);
            // The response, which contains the body and headers that are returned by the server.
            System.out.println(new Gson().toJson(resp.body));
            System.out.println(new Gson().toJson(resp.headers));
        }
    }