Use Alibaba Cloud SDKs for Java in an IDE
This topic describes how to use Alibaba Cloud SDKs for Java in an Integrated Development Environment (IDE) on Windows. In this example, IntelliJ IDEA is used.
Prerequisites
The Java Development Kit (JDK) is installed. For more information, see Install the JDK on Windows.
-
You have installed IntelliJ IDEA. If not, see Set up a Java development environment on Windows.
Use SDKs
Use a sample project provided in OpenAPI Explorer
-
Go to the OpenAPI Explorer page, and select a product and API. For example, to call the
DescribeInstanceTypeFamiliesAPI of ECS, enterDescribeInstanceTypeFamiliesin the search box and click the result to go to the OpenAPI Explorer page. -
On the Parameters tab in the middle column, specify the parameters based on your business requirements. When you specify the parameters, read the information on the Document tab in the rightmost column. Make sure that you understand the usage notes of the operation and the description of each parameter. Pay attention to billing-related information. In this example, the DescribeInstanceTypeFamilies operation supports two request parameters. You must specify a value such as cn-hangzhou for the RegionId parameter. The Generation parameter is optional. You can set this parameter to ecs-5, which indicates the V-series instance family. You can view the valid values of the parameters on the Document tab.
-
On the SDK Sample Code tab in the rightmost column, select a programming language and click Download Project to download the complete SDK project to your computer. Then, decompress the package.
NoteThe complete project contains the SDK information and the demo for calling the API operation.
-
Open IntelliJ IDEA, click File > Open, select the decompressed project folder, and wait for Maven to automatically install the dependencies.
Before you call this operation, you must obtain an AccessKey pair as the access credential. We recommend that you use the AccessKey pair of a Resource Access Management (RAM) user. For more information, see the Create an AccessKey pair for a RAM user section of the "Create an AccessKey pair" topic.
ImportantAfter you obtain the AccessKey pair of a RAM user, you must configure the AccessKey pair in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.
-
Run the SDK demo code.
In the left-side directory tree, double-click Sample to open it. Click the Run icon in the upper-right corner of the editor to run the code.
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sample; import com.aliyun.tea.*; public class Sample { /** * Initialize the account client with an AccessKey pair. * @return Client * @throws Exception */ public static com.aliyun.ecs20140526.Client createClient() throws Exception { // Leaking the project code may cause the AccessKey to be leaked and threaten the security of all resources under your account. The following code is for reference only. // We recommend that you use a more secure method, such as STS. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html. com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config() // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // For the endpoint, see https://api.aliyun.com/product/Ecs config.endpoint = "ecs.cn-beijing.aliyuncs.com"; return new com.aliyun.ecs20140526.Client(config); } } -
View the result. Click anywhere in the Run window in the lower part of the console and press
Ctrl+Fto search forstatusCode. If"statusCode":200is displayed, the call was successful.
Install an SDK in an existing project
-
Obtain the SDK.
Go to SDK Center and select the SDK for the cloud product you want to use. This example uses ECS. For SDK Version, select V2.0. For Language, select Java. For installation method, this example uses Apache Maven.
This SDK requires Java 8 or later. In your project's pom.xml file, add the dependency configuration where
groupIdiscom.aliyun,artifactIdisecs20140526, andversionis5.1.2. -
Import the SDK.
Open your Maven project in IntelliJ IDEA. In the pom.xml file, create a new <dependencies></dependencies> tag and copy the Apache Maven dependency from the previous step into this tag.
<dependencies> <!--ECS V2.0 SDK --> <dependency> <groupId>com.aliyun</groupId> <artifactId>ecs20140526</artifactId> <version>5.1.2</version> </dependency> </dependencies> -
Right-click the project name and choose Maven > Reload project to download the Maven dependency.
-
Create a Java class.
In the src/main/java directory of the project, right-click the java folder and choose New > Java Class. In this example, the Java class is named Sample.
-
Initialize the cloud service client.
ImportantYou must use an AccessKey pair to complete identity verification when you initialize the client. In this case, you must obtain an AccessKey pair in advance. For more information about how to obtain an AccessKey pair, see Create an AccessKey.
After you obtain the AccessKey pair of a RAM user, you must configure the AccessKey pair in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.
For more information about how to configure the endpoint, see Endpoints.
import com.aliyun.ecs20140526.Client; import com.aliyun.teaopenapi.models.Config; public class Sample { public static void main(String[] args) throws Exception { Config config = new Config() .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); config.endpoint = "ecs-cn-hangzhou.aliyuncs.com"; Client client = new Client(config); } } -
Call the API operation.
Before you call an API, you need to understand its details. For more information, see the API documentation.
In the Maven dependency for a cloud service, the cloud service SDK provides a request class and response class for each API operation. A request class defines the parameters and value types. A response class defines the response parameters. This prevents spelling mistakes when you call the operation.
For example, for the describeInstanceTypeFamilies operation, its request class is DescribeInstanceTypeFamiliesRequest and response class is DescribeInstanceTypeFamiliesResponse.
NoteNaming rule for request classes: API name + Request
Naming rule for response classes: API name + Response
import com.aliyun.ecs20140526.Client; import com.aliyun.ecs20140526.models.DescribeInstanceTypeFamiliesRequest; import com.aliyun.ecs20140526.models.DescribeInstanceTypeFamiliesResponse; import com.aliyun.teaopenapi.models.Config; public class Sample { public static void main(String[] args) throws Exception { Config config = new Config() .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); config.endpoint = "ecs-cn-hangzhou.aliyuncs.com"; Client client = new Client(config); DescribeInstanceTypeFamiliesRequest describeInstanceTypeFamiliesRequest = new DescribeInstanceTypeFamiliesRequest(); describeInstanceTypeFamiliesRequest.setRegionId("cn-hangzhou"); DescribeInstanceTypeFamiliesResponse describeInstanceTypeFamiliesResponse = client.describeInstanceTypeFamilies(describeInstanceTypeFamiliesRequest); } } -
Handle exceptions. Alibaba Cloud SDKs handle exceptions in a unified manner.
TeaException: This type of exceptions are caused by business errors. The following three parameters are provided to handle such an exception:
code: the error code that is returned when the exception occurs.
message: the error message that is returned when the exception occurs. The message contains the ID of the API request for which the exception is thrown.
data: the detailed error information that is returned by the server when an exception occurs.
import com.aliyun.ecs20140526.Client; import com.aliyun.ecs20140526.models.DescribeInstanceTypeFamiliesRequest; import com.aliyun.ecs20140526.models.DescribeInstanceTypeFamiliesResponse; import com.aliyun.tea.TeaException; import com.aliyun.teaopenapi.models.Config; public class Sample { public static void main(String[] args) { try { Config config = new Config() .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); config.endpoint = "ecs-cn-hangzhou.aliyuncs.com"; Client client = new Client(config); DescribeInstanceTypeFamiliesRequest describeInstanceTypeFamiliesRequest = new DescribeInstanceTypeFamiliesRequest(); describeInstanceTypeFamiliesRequest.setRegionId("cn-hangzhou"); DescribeInstanceTypeFamiliesResponse describeInstanceTypeFamiliesResponse = client.describeInstanceTypeFamilies(describeInstanceTypeFamiliesRequest); } catch (TeaException teaException) { // This is for demonstration only. Handle exceptions with care in your projects and do not ignore them. // Print the error code. System.out.println(teaException.getCode()); // Print the error message, which includes the RequestId. System.out.println(teaException.getMessage()); // Print the detailed error information returned by the server. System.out.println(teaException.getData()); } catch (Exception e) { TeaException error = new TeaException(e.getMessage(), e); // This is for demonstration only. Handle exceptions with care in your projects and do not ignore them. // Error message. System.out.println(error.getMessage()); // Diagnostic address. System.out.println(error.getData().get("Recommend")); com.aliyun.teautil.Common.assertAsString(error.message); } } }
FAQ
-
What do I do if the "java: error: release version X not supported" error message is returned when I run the code?
Press
Ctrl+Alt+Shift+Sto open the Project Structure dialog box. Click Modules in the left-side navigation pane. Select a value from the Language level drop-down list based on the JDK version that you use. For example, if you use JDK 8, select 8-Lambdas, type annotations etc. Click Apply and then click OK. -
What do I do if the "java: Compilationfailed: internal java compiler error" error message is returned when I run the code?
In the IntelliJ IDEA menu bar, click File > Settings > Build, Execution, Deployment > Compiler > Java Compiler. Set Project bytecode version and Target bytecode version to the version that matches your JDK. For example, if you use JDK 8, select 8 for both options. Click Apply, and then click OK.