Alibaba Cloud SDK V1.0 for Java supports generic API calls. This topic describes how to make generic calls by using Alibaba Cloud SDK V1.0 for Java.
Characteristics
Lightweight: You can use Alibaba Cloud SDK V1.0 for Java to call all API operations by installing only
aliyun-python-sdk-core, without the need to install the SDK of each service.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 the core library of Alibaba Cloud SDK V1.0 for Java
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(
// The region ID.
"cn-hangzhou",
// System.getenv specifies that the AccessKey ID of the Resource Access Management (RAM) user is obtained from the environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// System.getenv specifies that the AccessKey secret of the RAM user is obtained from the environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Optional. Configure HTTPS for the client.
HttpClientConfig clientConfig = HttpClientConfig.getDefault();
// // Disable server certificate authentication.
// clientConfig.setIgnoreSSLCerts(true);
// // Specify the maximum number of connections on each host.
// clientConfig.setMaxRequestsPerHost(6);
// // Specify the connection timeout period.
// clientConfig.setConnectionTimeoutMillis(30000L);
// // Specify timeout period for read requests.
// clientConfig.setReadTimeoutMillis(30000L);
// // Specify timeout period for write requests.
// clientConfig.setWriteTimeoutMillis(60000L);
// // Configure an HTTP proxy.
// clientConfig.setHttpProxy("http://127.0.0.1:9898");
// // Configure an HTTPS proxy.
// clientConfig.setHttpsProxy("http://user:password@127.0.0.1:8989");
// // Configure a list of addresses that skip proxying.
// 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.
Operation-specific 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.
Scenario | How the parameter is passed |
| putQueryParameter(String key,String value) Note To specify a set of key-values pairs, specify them in the following format: putQueryParameter("key.1","value1"); putQueryParameter("key.2","value2");... |
| 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.
// Initiate a request.
CommonResponse response = client.getCommonResponse(request);
// If the response to the response.getData() method is of the JSON type, the request ID and response parameters are returned.
System.out.println(response.getData());Sample code
Example: Call an RPC-style API operation
In this example, the DescribeInstanceStatus operation of ECS is called by 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 a DefaultAcsClient instance and initialize the instance.
DefaultProfile profile = DefaultProfile.getProfile(
// The region ID.
"cn-hangzhou",
// Obtain the AccessKey ID of a Resource Access Management (RAM) user from environment variables.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Obtain the AccessKey secret of the RAM user from environment variables.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
IAcsClient client = new DefaultAcsClient(profile);
// Create an API request and configure 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.
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.setSysProtocol(com.aliyuncs.http.ProtocolType.HTTPS); // The request protocol. Valid values: HTTP and HTTPS. 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 by 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 a DefaultAcsClient instance and initialize the instance.
DefaultProfile profile = DefaultProfile.getProfile(
// The region ID.
"cn-hangzhou",
// Obtain the AccessKey ID of the RAM user from the environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Obtain the AccessKey secret of the RAM user from the environment variable.
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
IAcsClient client = new DefaultAcsClient(profile);
// Create an API request and configure 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 URL of the API operation. When you call an ROA-style API operation, you must configure UriPattern() to specify a complete URL of the API operation. You can obtain the URL of an API operation from the API 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
What can I do if the "The input parameter 'AccessKeyId' that is mandatory for processing this request is not supplied" error message is returned?
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.
Sample error request:
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.
Sample success request:
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
What can I do if the "com.aliyuncs.exceptions.ClientException: MissingParameter : The input parameter "Timestamp" that is mandatory for processing this request is not supplied" error message is returned?
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.