Install the Java SDK

更新时间:
复制 MD 格式

This topic describes how to install and use the Java SDK. An example is provided to show you how to call the GetProject API of Function AI. For more information about the GetProject API, see GetProject - Query a project.

Prerequisites

  • Create an AccessKey pair

    API calls to Alibaba Cloud require an AccessKey pair. An AccessKey pair from an Alibaba Cloud account provides full access to your resources. If this AccessKey pair is leaked, your resources are at risk. To improve security, we recommend that you use an AccessKey pair from a Resource Access Management (RAM) user and grant the RAM user only the necessary permissions.

  • Configure the AccessKey pair in an environment variable

    For more information, see Configure environment variables on Linux, macOS, and Windows.

Environment requirements

Java 8 or later is required.

Installation method

The Java SDK supports multiple installation methods. This topic uses Apache Maven as an example. For more information about other installation methods, see SDK Center.

Open the pom.xml file of your Maven project. Add the dependency configuration to the <dependencies> node and then refresh the Maven configuration.

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>devs20230714</artifactId>
  <version>2.4.1</version>
</dependency>

Use the SDK

1. Initialize the client

All API calls in the SDK are made through a client object. Before you make an API call, you must initialize the client. You can initialize the client in several ways. This example shows how to initialize the client using an AccessKey pair. For more information about other initialization methods, see Manage access credentials.

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

public class Sample {
    private static Client createClient() throws Exception {
        Config config = new Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // For the endpoint, see https://api.aliyun.com/product/Devs
                .setEndpoint("devs.cn-hangzhou.aliyuncs.com");
        return new Client(config);
    }
}

2. Build the API request object

Before you make a call, refer to the API documentation to obtain information about the required parameters.

Note

Unlike some APIs that require you to build a complex request object, the main parameter of the GetProject API, projectName, is passed as a string.

// Prepare the name of the project to query.
String projectName = "my-devs-project"; // Replace this with the actual name of your project.

3. Make the call

When you call an API through the client, you can set runtime parameters, such as timeout and agent configurations. For more information, see Advanced configurations.

Note

The naming convention for the API response object is {APIName}Response. For example, the response object for the GetProject API is GetProjectResponse.

// Set runtime parameters.
RuntimeOptions runtime = new RuntimeOptions();
java.util.Map<String, String> headers = new java.util.HashMap<>();

// Call the GetProject API.
GetProjectResponse response = client.getProjectWithOptions(projectName, headers, runtime);
// Print the body of the response in JSON format.
System.out.println(com.aliyun.teautil.Common.toJSONString(response.getBody()));

4. Handle exceptions

The Java SDK provides detailed exception classification. The main exceptions are TeaUnretryableException and TeaException.

  • TeaUnretryableException: This exception is typically caused by network issues. It is thrown after the maximum number of retries for a network request is reached.

  • TeaException: This exception indicates a service-related error, such as an invalid parameter or an authentication failure.

For more information about exception handling, see Exception handling.

Important

You must take appropriate measures to handle exceptions, such as propagating exceptions, recording logs, and attempting to recover. This ensures the robustness and stability of your system.

5. Complete example

import com.aliyun.devs20230714.Client;
import com.aliyun.devs20230714.models.GetProjectResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaUnretryableException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class Sample {
    private static Client createClient() throws Exception {
        Config config = new Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // For the endpoint, see https://api.aliyun.com/product/Devs
                .setEndpoint("devs.cn-hangzhou.aliyuncs.com");
        return new Client(config);
    }

    public static void main(String[] args) {
        try {
            Client client = Sample.createClient();
            
            // Prepare the name of the project to query.
            String projectName = "my-devs-project"; // Replace this with the actual name of your project.

            // Set runtime parameters.
            RuntimeOptions runtime = new RuntimeOptions();
            java.util.Map<String, String> headers = new java.util.HashMap<>();
            
            // Call the GetProject API.
            GetProjectResponse response = client.getProjectWithOptions(projectName, headers, runtime);
            
            System.out.println("The API call is successful!");
            System.out.println(com.aliyun.teautil.Common.toJSONString(response.getBody()));

        } catch (TeaUnretryableException ue) {
            // This is for printing and demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
            System.err.println("A non-retriable network exception occurred: ");
            ue.printStackTrace();
            System.err.println("Error message: " + ue.getMessage());
            System.err.println("Original request: " + ue.getLastRequest());
        } catch (TeaException e) {
            // This is for printing and demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
            System.err.println("An API service exception occurred: ");
            e.printStackTrace();
            System.err.println("Error code: " + e.getCode());
            System.err.println("Error message: " + e.getMessage());
            System.err.println("RequestId: " + e.getData().get("RequestId"));
        } catch (Exception e) {
            // This is for printing and demonstration purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
            System.err.println("An unknown exception occurred: ");
            e.printStackTrace();
        }
    }
}

More information

In addition to the method described, you can also use generalized calls to call the Function AI OpenAPI. For more information, see Generalized calls.