Generalized calls

Updated at:
Copy as MD

Alibaba Cloud SDK for Java V2.0 supports generic API calls, which allow you to call any OpenAPI operation without installing service-specific SDKs.

Features

Lightweight: Only the Alibaba Cloud core SDK is required. No additional product SDKs are needed.

Easy to use: Build a unified parameter object and use a common client to call any API. Responses are returned in a unified standard format.

For more information, see Generalized and specialized calls.

Usage notes

Before using generalized calls, review the OpenAPI metadata or the product development reference in Help Center to obtain the API style, version, and request parameters.

Install the core SDK

Add the following dependency to your pom.xml file. For the latest version, see Maven Central.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-gateway-pop</artifactId>
    <version>last-version</version>
</dependency>

Call an OpenAPI

1. Initialize the asynchronous client

All OpenAPI calls use methods from a com.aliyun.sdk.gateway.pop.clients.CommonAsyncClient instance. Initialize the asynchronous client and configure an access credential provider before making calls. The following example uses a static credential provider. For other credential options, see Manage access credentials.

Note
  • The asynchronous client is thread-safe. We recommend using the singleton pattern to ensure only one instance is created per access credential and Endpoint throughout the application lifecycle.

  • The SDK uses a connection pool to manage asynchronous HTTP requests by default. To customize pool parameters, see HTTP connection pool configuration.

  • For more information about client configurations, see Advanced configurations.

Example:

// Use StaticCredentialProvider as an example.
com.aliyun.auth.credentials.provider.StaticCredentialProvider provider = com.aliyun.auth.credentials.provider.StaticCredentialProvider.create(
        com.aliyun.auth.credentials.Credential.builder()
                // Required. Obtain the AccessKey ID of the Resource Access Management (RAM) user from the environment variable.
                .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Obtain the AccessKey secret of the RAM user from the environment variable.
                .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                .build()
);
// Create a CommonAsyncClient instance.
com.aliyun.sdk.gateway.pop.clients.CommonAsyncClient client = com.aliyun.sdk.gateway.pop.clients.CommonAsyncClient.builder()
        .credentialsProvider(provider)
        .overrideConfiguration(
                darabonba.core.client.ClientOverrideConfiguration.create()
                        // Set the request protocol. This parameter is optional. The default protocol is HTTPS.
                        .setProtocol("HTTPS")
                        // Set the Endpoint of the cloud product. This parameter is required. For more information about how to set an Endpoint, see Endpoint configuration.
                        .setEndpointOverride("<ENDPOINT>")
        )
        .build();

2. Configure call parameters

Configure call parameters using com.aliyun.sdk.gateway.pop.models.CommonRequest, which includes basic OpenAPI information and API request parameters.

Basic OpenAPI information parameters:

Parameter

Description

product

The product code. You can obtain it from the metadata. Examples: ECS and RAM.

version

The API version. You can obtain it from the metadata. For example, the API version of ECS is 2014-05-26.

action

The OpenAPI name. For example, the OpenAPI name for querying the list of ECS instances is DescribeInstances.

path

The resource path. You can obtain it from the metadata. For RPC APIs, the value of this parameter is /. For ROA APIs, the value is the specific resource path. For example, the resource path for the API to create an index in Model Studio is /{WorkspaceId}/index/create, where {WorkspaceId} must be replaced with a specific business value.

httpMethod

The request method. The default value is GET.

requestBodyType

The type of the request body. Valid values: json and form. The default value is json. The choice depends on the API request parameters.

API request parameters:

Pass request parameters using putQueryParameters, putBodyParameters, or putBodyStream based on the metadata description. For example, the metadata of DescribeInstances contains {"name":"RegionId","in":"query",...}}. The "in":"query" field indicates that RegionId must be passed using putQueryParameters.

Parameter

Description

putQueryParameters

If a request parameter has "in":"query", pass it using putQueryParameters. You can use the default value for requestBodyType.

putBodyParameters

If a request parameter has "in":"body" or "in": "formData", pass it using putBodyParameters. Set requestBodyType based on the request body type.

putBodyStream

For file upload scenarios, pass the file stream using putBodyStream. You can use the default value for requestBodyType.

Example:

// Example 1: Set query parameters ("query").
com.aliyun.sdk.gateway.pop.models.CommonRequest commonRequest = com.aliyun.sdk.gateway.pop.models.CommonRequest.builder()
        .product("ECS")
        .version("2014-05-26")
        .action("DescribeInstances")
        .path("/")
        .httpMethod(com.aliyun.core.http.HttpMethod.POST) // The request method. This parameter is optional. The default value is HttpMethod.GET.
        .putQueryParameters("RegionId", "cn-chengdu")
        .putQueryParameters("InstanceIds", new com.google.gson.Gson().toJson(java.util.Collections.singletonList("i-2vc6*************")))
        .build();

//        // Example 2: Set body parameters ("formData"). Set the value of requestBodyType to form.
//        com.aliyun.sdk.gateway.pop.models.CommonRequest commonRequest = com.aliyun.sdk.gateway.pop.models.CommonRequest.builder()
//                .product("alimt")
//                .version("2018-10-12")
//                .action("TranslateGeneral")
//                .path("/")
//                .httpMethod(com.aliyun.core.http.HttpMethod.POST)
//                .requestBodyType("form") // The request body type is form.
//                .putBodyParameters("FormatType", "text")
//                .putBodyParameters("SourceLanguage", "en")
//                .putBodyParameters("TargetLanguage", "zh")
//                .putBodyParameters("SourceText", "hello")
//                .putBodyParameters("Scene", "general")
//                .build();

//        // Example 3: Set body parameters ("body"). Set the value of requestBodyType to json.
//        com.aliyun.sdk.gateway.pop.models.CommonRequest commonRequest = com.aliyun.sdk.gateway.pop.models.CommonRequest.builder()
//                .product("bailian")
//                .version("2023-12-29")
//                .action("AddCategory")
//                .path("/llm-p2e4************/datacenter/category")
//                .httpMethod(com.aliyun.core.http.HttpMethod.POST)
//                .requestBodyType("json")
//                .putBodyParameters("CategoryName", "test_category")
//                .putBodyParameters("CategoryType", "UNSTRUCTURED")
//                .build();

//        // Example 4: Use a Stream parameter to pass a file stream.
//        java.io.InputStream io = new java.io.ByteArrayInputStream(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get("D:\\test.jpeg")));
//        com.aliyun.sdk.gateway.pop.models.CommonRequest commonRequest = com.aliyun.sdk.gateway.pop.models.CommonRequest.builder()
//                .product("ocr")
//                .version("2021-07-07")
//                .action("RecognizeGeneral")
//                .path("/")
//                .httpMethod(com.aliyun.core.http.HttpMethod.POST)
//                .putBodyStream(io)
//                .build();

3. Send the request

Call the callApi method on the asynchronous client from Step 1, passing the CommonRequest instance from Step 2.

java.util.concurrent.CompletableFuture<com.aliyun.sdk.gateway.pop.models.CommonResponse> responseCompletableFuture = client.callApi(commonRequest);
com.aliyun.sdk.gateway.pop.models.CommonResponse response = responseCompletableFuture.join();

Complete code example

import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.gateway.pop.models.CommonRequest;
import com.aliyun.sdk.gateway.pop.models.CommonResponse;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import com.aliyun.core.http.HttpClient;

import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;

public class Demo {
    public static void main(String[] args) throws IOException {
        com.aliyun.auth.credentials.provider.StaticCredentialProvider provider = com.aliyun.auth.credentials.provider.StaticCredentialProvider.create(
                com.aliyun.auth.credentials.Credential.builder()
                        // Required. Obtain the AccessKey ID of the RAM user from the environment variable.
                        .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                        // Required. Obtain the AccessKey secret of the RAM user from the environment variable.
                        .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                        .build()
        );
        HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                // Connection pool parameters
                .maxConnections(128) // The size of the connection pool. Default value: 128.
                .maxConnectionsPerRoute(128) // The maximum number of connections per route. Default value: 128.
                .maxIdleTimeOut(Duration.ofMillis(20000)) // The maximum idle time of a connection in the connection pool. Default value: 30,000 milliseconds.
                .keepAlive(Duration.ofMillis(20000)) // The idle time to live of a connection. Default value: 20,000 milliseconds.
                .connectRequestTimeout(Duration.ofMillis(30000)) // The timeout period for obtaining a connection. Default value: 30,000 milliseconds.
                // When you use the HTTPS protocol, you can configure SSL/TLS parameters.
                // .x509TrustManagers(null) // Configure a custom CA certificate trust manager. This parameter is optional.
                // .keyManagers(null) // Configure a client key manager. This parameter is optional.
                // .ignoreSSL(false) // Specifies whether to skip certificate verification. Default value: false. This parameter is optional.
                // .hostnameVerifier(null) // A custom HTTPS hostname verification rule. You must implement javax.net.ssl.HostnameVerifier. This parameter is optional.
                // Proxy configuration parameters
                .proxy(new com.aliyun.core.http.ProxyOptions(
                        com.aliyun.core.http.ProxyOptions.Type.HTTP,
                        new java.net.InetSocketAddress("<YOUR-PROXY-HOSTNAME>", 9001) // The proxy address and port number.
                ).setCredentials("<YOUR-PROXY-USERNAME>", "<YOUR-PROXY-PASSWORD>"))
                // Timeout period
                .connectionTimeout(Duration.ofMillis(10000)) // The default connection timeout is 10,000 milliseconds.
                .responseTimeout(Duration.ofMillis(20000)) // The default response timeout is 20,000 milliseconds.
                .build();

        com.aliyun.sdk.gateway.pop.clients.CommonAsyncClient client = com.aliyun.sdk.gateway.pop.clients.CommonAsyncClient.builder()
                .credentialsProvider(provider)
                .httpClient(httpClient)
                .build();

        // Example 1: Set query parameters ("query").
        CommonRequest commonRequest = CommonRequest.builder()
                .product("ECS")
                .version("2014-05-26")
                .action("DescribeInstances")
                .path("/")
                .httpMethod(com.aliyun.core.http.HttpMethod.POST) // The request method. This parameter is optional. The default value is HttpMethod.GET.
                .putQueryParameters("RegionId", "cn-chengdu")
                .putQueryParameters("InstanceIds", new Gson().toJson(Collections.singletonList("i-2vc6*************")))
                .requestConfiguration(RequestConfiguration.create()
                        .setEndpointOverride("ecs.cn-chengdu.aliyuncs.com")) // The ECS Endpoint.
                .build();

        // Example 2: Set body parameters ("formData"). Set the value of requestBodyType to form.
//        com.aliyun.sdk.gateway.pop.models.CommonRequest commonRequest = com.aliyun.sdk.gateway.pop.models.CommonRequest.builder()
//                .product("alimt")
//                .version("2018-10-12")
//                .action("TranslateGeneral")
//                .path("/")
//                .httpMethod(com.aliyun.core.http.HttpMethod.POST)
//                .requestBodyType("form") // The request body type is form.
//                .putBodyParameters("FormatType", "text")
//                .putBodyParameters("SourceLanguage", "en")
//                .putBodyParameters("TargetLanguage", "zh")
//                .putBodyParameters("SourceText", "hello")
//                .putBodyParameters("Scene", "general")
//                .requestConfiguration(RequestConfiguration.create()
//                        .setEndpointOverride("mt.aliyuncs.com")) // The alimt Endpoint.
//                .build();

        // Example 3: Set body parameters ("body"). Set the value of requestBodyType to json.
//        com.aliyun.sdk.gateway.pop.models.CommonRequest commonRequest = com.aliyun.sdk.gateway.pop.models.CommonRequest.builder()
//                .product("bailian")
//                .version("2023-12-29")
//                .action("AddCategory")
//                .path("/llm-p2e4************/datacenter/category")
//                .httpMethod(com.aliyun.core.http.HttpMethod.POST)
//                .requestBodyType("json")
//                .putBodyParameters("CategoryName", "test_category")
//                .putBodyParameters("CategoryType", "UNSTRUCTURED")
//                .requestConfiguration(RequestConfiguration.create()
//                        .setEndpointOverride("bailian.cn-beijing.aliyuncs.com")) // The Model Studio Endpoint.
//                .build();

        // Example 4: Use a Stream parameter to pass a file stream.
//        java.io.InputStream io = new java.io.ByteArrayInputStream(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get("D:\\test.jpeg")));
//        com.aliyun.sdk.gateway.pop.models.CommonRequest commonRequest = com.aliyun.sdk.gateway.pop.models.CommonRequest.builder()
//                .product("ocr")
//                .version("2021-07-07")
//                .action("RecognizeGeneral")
//                .path("/")
//                .httpMethod(com.aliyun.core.http.HttpMethod.POST)
//                .putBodyStream(io)
//                .requestConfiguration(RequestConfiguration.create()
//                        .setEndpointOverride("ocr-api.cn-hangzhou.aliyuncs.com")) // The OCR Endpoint.
//                .build();

        CompletableFuture<CommonResponse> responseCompletableFuture = client.callApi(commonRequest);
        CommonResponse response = responseCompletableFuture.join();
        System.out.println(response.getHeaders());
        System.out.println(new Gson().toJson(response.getBody()));
    }
}