Generalized calls
Alibaba Cloud SDK V1.0 for Java supports generic API calls. This topic describes how to make generic calls using Alibaba Cloud SDK V1.0 for Java.
Characteristics
Lightweight: You only need to install
aliyun-java-sdk-coreto call all OpenAPI without installing individual product SDKs.Fast iteration and compatibility: If a cloud service does not provide an SDK, or the SDK is not updated for the latest API operations, you can make generic calls. This way, you can call the latest API operations without the need to wait for SDK updates.
For more information, see Generic calls and specialized calls.
Usage notes
Before you make a generic call, manually obtain and specify the required metadata, including the API version, request URL, and parameter type. For more information, see API metadata.
Install Core SDK
Add the following dependency to the pom.xml file to install the core library of Alibaba Cloud SDK V1.0 for Java.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
// Select a version.
<version>[(4.0.0,5.0.0)]</version>
</dependency>Call an API operation
Initialize a request client
In the com.aliyuncs package, create a client module to initialize the request client, and use the client to call API operations. In this example, an AccessKey pair is used to initialize the request client. For more information, see Manage access credentials.
To prevent AccessKey leaks, you can record the AccessKey pair in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
// 1. Create and initialize a DefaultAcsClient instance.
DefaultProfile profile = DefaultProfile.getProfile(
// Your region ID.
"cn-hangzhou",
// System.getenv indicates that the AccessKey ID of the Resource Access Management (RAM) user is obtained from an environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// System.getenv indicates that the AccessKey secret of the RAM user is obtained from an environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Optional. Configure HTTPS for the client.
HttpClientConfig clientConfig = HttpClientConfig.getDefault();
// // Do not verify the server-side certificate.
// clientConfig.setIgnoreSSLCerts(true);
// // The maximum number of connections for each host.
// clientConfig.setMaxRequestsPerHost(6);
// // The connection timeout.
// clientConfig.setConnectionTimeoutMillis(30000L);
// // The read timeout.
// clientConfig.setReadTimeoutMillis(30000L);
// // The write timeout.
// clientConfig.setWriteTimeoutMillis(60000L);
// // Set an HTTP proxy.
// clientConfig.setHttpProxy("http://127.0.0.1:9898");
// // Set an HTTPS proxy.
// clientConfig.setHttpsProxy("http://user:password@127.0.0.1:8989");
// // Set a list of addresses to ignore for the proxy.
// clientConfig.setNoProxy("127.0.0.1,localhost");
profile.setHttpClientConfig(clientConfig);
IAcsClient client = new DefaultAcsClient(profile);
Configure the basic information and request parameters of the API operation
Use CommonRequest to configure the common request parameters and operation-specific parameters for the API operation. For more information about the common request parameters, see Advanced settings.
The CommonRequest module is used to convert the API metadata, such as the version number, URL, and parameter type, to a valid HTTP request through a standard request configuration process, and then return the original response data. How parameters are passed are determined by the API style and design.
API Request Parameters
How a request parameter is passed is determined by the metadata of the API operation. For example, the DescribeInstanceStatus API operation is defined as {"name":"RegionId","in":"query",...}} in the metadata. In this case, "in":"query" indicates that the region ID (RegionId) must be passed in putQueryParameter.
Description | How the parameter is passed |
This applies when the request parameter is set to | putQueryParameter(String key,String value) Note If a request parameter is a collection, you can specify the parameter as putQueryParameter("key.1","value1"); You can pass parameters using the putQueryParameter("key.2","value2");... format. |
This applies when the request parameter is | putBodyParameter(String key,String value) Note If the request parameter does not specify a string, convert the parameter value to a JSON string and specify the string as the variable value. Example: request.putBodyParameter("key",new Gson().toJson(value)); |
Upload files | setHttpContent(byte[] content,String charset,FormatType formatType) Note Set formatType to FormatType.RAW. |
// 2. Create an API request and configure the request parameters.
// This example shows how to create a request to call the DescribeInstanceStatus operation, which is used to obtain the status of an Elastic Compute Service (ECS).
CommonRequest request = new CommonRequest();
// 2.1 Configure the common request parameters.
request.setSysMethod(com.aliyuncs.http.MethodType.POST);
request.setSysDomain("ecs-cn-hangzhou.aliyuncs.com");// The domain name of the API operation.
request.setSysVersion("2014-05-26");// The API version.
request.setSysAction("DescribeInstanceStatus"); // The name of the API operation. When you call an RPC-style API operation, you must configure SysAction() to specify the name of the API operation.
request.setSysConnectTimeout(30000); // The timeout period.
request.setSysProtocol(com.aliyuncs.http.ProtocolType.HTTPS); // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
// request.setSysUriPattern("/"); // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. Do not configure this parameter for RPC-style API operations.
// 2.2 Configure operation-specific request parameters.
// Scenario 1: Specify the query parameters in putQueryParameter(string key,string value).
request.putQueryParameter("RegionId", "cn-hangzhou");
List<String> instanceIds = List.of(
"i-bp1axhql4dqXXXXXXXX",
"i-bp124uve8zqXXXXXXXX"
);
for(int i = 0; i < instanceIds.size(); ++i) {
request.putQueryParameter("InstanceId." + (i + 1), (String)instanceIds.get(i));
}
request.putQueryParameter("PageNumber", "1");
request.putQueryParameter("PageSize", "30");
// Scenario 2: Specify the body parameters in putBodyParameter(string key,string value).
// request.putBodyParameter("key1", "value1");
// request.putBodyParameter("key2", "value2");
// request.putBodyParameter("key3", "value3");
// Scenario 3: To upload files, specify setHttpContent(byte[] content,String charset,FormatType formatType). Set formatType to FormatType.RAW.
// byte[] bodyImg = Files.readAllBytes(Paths.get("<FILE_PATH>")); // Replace <FILE_PATH> with the actual file path.
// request.setHttpContent(bodyImg, "UTF-8", FormatType.RAW);
Initiate a request
Use the client to call the getCommonResponse method.
// Send the request.
CommonResponse response = client.getCommonResponse(request);
// The return value, response.getData(), is JSON-formatted data that contains the RequestId and the OpenAPI return parameters.
System.out.println(response.getData());Sample code
Example: Call an RPC-style API operation
In this example, the DescribeInstanceStatus operation of ECS is called using CommonRequest.
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.GsonBuilder;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class Sample {
public static void main(String[] args) throws ClientException, UnsupportedEncodingException {
// Create and initialize a DefaultAcsClient instance.
DefaultProfile profile = DefaultProfile.getProfile(
// Your region ID.
"cn-hangzhou",
// Obtain the AccessKey ID of the RAM user from an environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Obtain the AccessKey secret of the RAM user from an environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
IAcsClient client = new DefaultAcsClient(profile);
// Create an API request and set parameters.
CommonRequest request = new CommonRequest();
request.setSysMethod(com.aliyuncs.http.MethodType.POST); // The request method.
request.setSysDomain("ecs-cn-hangzhou.aliyuncs.com"); // The domain name of the API operation.
request.setSysVersion("2014-05-26"); // The API version number.
request.setSysAction("DescribeInstanceStatus"); // The name of the API operation. When you call an RPC-style API operation, you must configure SysAction() to specify the operation name.
request.setSysProtocol(com.aliyuncs.http.ProtocolType.HTTPS); // The request protocol. Valid values: HTTPS and HTTP. We recommend that you use HTTPS.
request.putQueryParameter("RegionId", "cn-hangzhou");
List<String> instanceIds = List.of(
"i-bp1axhql4dqXXXXXXXX",
"i-bp124uve8zqXXXXXXXX"
);
for(int i = 0; i < instanceIds.size(); ++i) {
request.putQueryParameter("InstanceId." + (i + 1), (String)instanceIds.get(i));
}
request.putQueryParameter("PageNumber", "1");
request.putQueryParameter("PageSize", "30");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Example: Call a RESTful API operation
In this example, the DescribeClustersV1 operation of Container Service for Kubernetes (ACK) is called using CommonRequest.
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
public class Sample {
public static void main(String[] args) {
// Create and initialize a DefaultAcsClient instance.
DefaultProfile profile = DefaultProfile.getProfile(
// Your region ID.
"cn-hangzhou",
// Obtain the AccessKey ID of the RAM user from an environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Obtain the AccessKey secret of the RAM user from an environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
IAcsClient client = new DefaultAcsClient(profile);
// Create an API request and set parameters.
CommonRequest request = new CommonRequest();
request.setSysDomain("cs.aliyuncs.com");// The domain name.
request.setSysVersion("2015-12-15");// The API version.
request.setSysUriPattern("/clusters"); // The URI of the API resource. When you call a ROA-style API operation, you must configure UriPattern() to specify the complete resource path. Obtain the resource path from data.path in the OpenAPI metadata.
request.setSysMethod(MethodType.GET);// The request method.
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}FAQ
The error message indicates that the required "AccessKeyId" parameter is missing.
Cause: The AccessKey pair is not correctly configured.
Solutions:
Run the following commands to check whether the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
Linux/macOS
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRETWindows
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%If a valid AccessKey pair is returned, the environment variables are properly configured. If no AccessKey pair or an invalid AccessKey pair is returned, configure the environment variables as required. For more information, see Configure environment variables in Linux, macOS, and Windows.
Check for errors related to the AccessKey pair in the code.
Examples of common errors:
accessKeyId = System.getenv("yourAccessKeyID"), accessKeySecret = System.getenv("yourAccessKeySecret")NoteIn the preceding sample error request, the input values of System.getenv() are used as the AccessKey pair. However, this function is used to read values from the environment variables. After you specify the environment variable names as ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET on your machine, System.getenv can read the values from the environment variables.
Correct example
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
The request fails with the following error message: "com.aliyuncs.exceptions.ClientException: MissingParameter : The input parameter "Timestamp" that is mandatory for processing this request is not supplied."
Cause: The
SysUriPatternparameter is configured in the common request parameters of the RPC-style API operation.Solution: Remove the
SysUriPatternparameter from the common request parameters.