To call an OpenAPI, you must integrate an SDK into your project. An SDK simplifies development, accelerates feature integration, and reduces maintenance costs. Integrating an Alibaba Cloud SDK involves three steps: importing the SDK, setting access credentials, and using the SDK. This topic describes how to perform this integration.
Prerequisites
JDK 1.8 or later.
Import the SDK
Log on to SDK Center and select the product that you want to use, such as Short Message Service (SMS).
On the Install page, set All Languages to Java. Then, on the Quick Start tab, find the Short Message Service (SMS) SDK installation method.

Set access credentials
To call an Alibaba Cloud OpenAPI, you must set your access credentials. Common credential types include AccessKey and Security Token Service (STS) token. To prevent credential leaks, we recommend storing them as environment variables. For more information about security solutions, see Securely use access credentials. This topic uses the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables as an example:
Configure environment variables in Linux and macOS
Configure environment variables by using the export command
The temporary environment variables configured by using the export command are valid only for the current session. After you exit the session, the configured environment variables become invalid. To configure permanent environment variables, you can add the export command to the startup configuration file of the corresponding operating system.
Configure the AccessKey ID and press Enter.
# Replace <ACCESS_KEY_ID> with your AccessKey ID. export ALIBABA_CLOUD_ACCESS_KEY_ID=yourAccessKeyIDConfigure the AccessKey secret and press Enter.
# Replace <ACCESS_KEY_SECRET> with your AccessKey secret. export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecretCheck whether the configuration is successful.
Run the
echo $ALIBABA_CLOUD_ACCESS_KEY_IDcommand. If the valid AccessKey ID is returned, the environment variables are configured.
Configure environment variables in Windows
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: LTAI****************
AccessKey Secret
Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET
Variable value: yourAccessKeySecret
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%andecho %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 yourAccessKeyID /M setx ALIBABA_CLOUD_ACCESS_KEY_SECRET yourAccessKeySecret /M/Mindicates that the environment variable is of system level. You can choose not to 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%andecho %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', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [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', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::Machine)Configure temporary environment variables. The environment variables apply only to the current session.
$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "yourAccessKeyID"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "yourAccessKeySecret"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.
Use the SDK
This topic uses the SendMessageToGlobe API of Short Message Service (SMS) as an example. For more information about the SendMessageToGlobe API, see SendMessageToGlobe.
1. Initialize the request client
In the SDK, all OpenAPI calls are initiated from a request client (Client). Before you can call an OpenAPI, you must initialize the request client. The request client can be initialized in multiple ways. This example shows how to use an AccessKey to initialize the client. For more information about initialization methods, see Manage access credentials.
Client objects, such as `Client` instances, are thread-safe. You can use them in multi-threaded environments without creating a separate instance for each thread.
In your development, do not frequently create client objects using the `new` keyword. This practice can lead to resource waste and performance degradation. We recommend that you use the singleton pattern to encapsulate the client. This ensures that only one client object is initialized for the same access credentials and endpoint throughout the application lifecycle.
public static com.aliyun.dysmsapi20180501.Client createClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// See https://api.alibabacloud.com/product/Dysmsapi.
config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20180501.Client(config);
}2. Create a request object
When you call an OpenAPI, you can use the request object provided by the SDK to pass parameters. The request object for an OpenAPI is named in the <OpenAPIName>Request format. For example, the request object for the SendSms API is SendSmsRequest. For more information about request parameters, see the API documentation for SendMessageToGlobe.
If an OpenAPI does not support request parameters, you do not need to create a request object. For example, when you call DescribeCdnSubList, the API does not support request parameters.
com.aliyun.dysmsapi20180501.models.SendMessageToGlobeRequest sendMessageToGlobeRequest = new com.aliyun.dysmsapi20180501.models.SendMessageToGlobeRequest()
.setTo("8521245567****")
.setMessage("Hello");3. Initiate a request
When you use a request client to call an OpenAPI, we recommend using a function in the <apiName>WithOptions format, where <apiName> is the name of the OpenAPI in camel case. This function takes two parameters: the request object from the previous step and a runtime parameter. The runtime parameter configures request behavior, such as timeout settings and proxy configurations. For more information, see Advanced configuration.
If an OpenAPI does not support request parameters, you do not need to pass a request object when you initiate the request. For example, when you call DescribeCdnSubList, you only need to pass the runtime parameter.
A response object for an OpenAPI is named in the <OpenAPIName>Response format. For example, the response object for the SendSms API is SendSmsResponse.
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
Client client = createClient();
// call api
client.sendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);4. Handle exceptions
The Java SDK classifies exceptions into `TeaUnretryableException` and `TeaException`.
`TeaUnretryableException`: This exception is typically caused by network issues and is thrown after the maximum number of retries is reached.
`TeaException`: This exception is mainly caused by business errors.
For more information about exception handling, see Exception handling.
Take appropriate measures to handle exceptions, such as propagating exceptions, recording logs, and attempting recovery, to ensure the robustness and stability of your system.
View the complete code sample
Special scenario: Configure the Advance interface for file uploads
When you use cloud products such as Image Search and Visual Intelligence API to process or upload local images, the OpenAPI provided in the official documentation may not directly support file uploads. To upload a file in this case, you can use the Advance interface provided by the cloud product. This interface supports passing a file stream object. The underlying implementation mechanism is as follows: The cloud product temporarily stores the uploaded file in Alibaba Cloud Object Storage Service (OSS). The default storage region is cn-shanghai. The product then reads the temporary file from OSS to implement the related features. This topic uses the DetectBodyCount interface of Visual Intelligence API - Face and Body as an example:
Temporary files stored in Alibaba Cloud OSS are cleared at regular intervals.
Initialize the request client
You must set both the
regionIdand theendpointof the cloud product. TheregionIdspecifies the region where the temporary file is stored in OSS. If you do not set theregionId, you may encounter issues such as timeouts when you call the OpenAPI because the cloud product and OSS are in different regions.public static com.aliyun.facebody20191230.Client createClient() throws Exception { com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config() // Required. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") gets the AccessKey ID from the environment variable. .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) // Required. System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") gets the AccessKey secret from the environment variable. .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); config.regionId = "cn-shanghai"; config.endpoint = "facebody.cn-shanghai.aliyuncs.com"; return new com.aliyun.facebody20191230.Client(config); }Create a request object
Create a
<OpenAPIName>AdvanceRequestobject to pass the file stream. For more information about the parameter name and type, see the<OpenAPIName>AdvanceRequestsource file. For example, the parameter name supported byDetectBodyCountAdvanceRequestisimageURLObject, and its type isInputStream.com.aliyun.facebody20191230.models.DetectBodyCountAdvanceRequest detectBodyCountAdvance = new com.aliyun.facebody20191230.models.DetectBodyCountAdvanceRequest() .setImageURLObject(Files.newInputStream(Paths.get("<FILE_PATH>"))); // Replace <FILE_PATH> with the actual file path.Initiate a request
Call the
<apiName>Advancefunction to initiate the request.com.aliyun.facebody20191230.Client client = createClient(); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); // Initiate the request. com.aliyun.facebody20191230.models.DetectBodyCountResponse resp = client.detectBodyCountAdvance(detectBodyCountAdvance, runtime);
FAQ
The error message "You are not authorized to perform this operation." is returned when I call an OpenAPI.
Cause: The Resource Access Management (RAM) user that corresponds to the AccessKey that you are using does not have the permissions to call the API.
Solution: Grant the required OpenAPI permissions to the RAM user. For more information about how to grant permissions to a RAM user, see Grant permissions to a RAM user.
For example, if the "You are not authorized to perform this operation." error is returned when you call SendMessageToGlobe, you can create the following custom policy and grant the corresponding permissions to the RAM user.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "dysms:SendMessageToGlobe", "Resource": "*" } ] }The error message "The specified endpoint can't operate this region." is returned when I call an OpenAPI.
Cause: The OpenAPI that you are calling does not support the endpoint that you specified when you initialized the request client.
Solution: See Endpoint configuration, modify the endpoint, and call the OpenAPI again.
The error message "java.lang.NullPointerException..." is returned when I call an OpenAPI.
Cause: Your AccessKey was not passed correctly.
Solution: When you initialize the request client, check whether the AccessKey is passed correctly. Note that
System.getenv("XXX")retrieves the value ofXXXfrom the environment variable.
For more solutions to errors that occur when you use the SDK, see FAQ.