Todos los productos
Search
Centro de documentos

Alibaba Cloud SDK:Llamadas genéricas

Última actualización: Sep 05, 2026

Alibaba Cloud SDK for Java V2.0 es compatible con las llamadas a API genéricas. Estas permiten invocar cualquier operación de openapi sin necesidad de instalar los SDK específicos de cada servicio.

Beneficios

Ligero: solo se requiere la biblioteca principal del SDK. No necesita los SDK específicos de cada servicio.

Fácil de usar: construya los parámetros comunes de la solicitud, invoque un cliente común y reciba las respuestas en un formato estándar.

Para obtener más información, consulte Generic calls and specialized calls.

Antes de empezar

Antes de ejecutar una llamada genérica, consulte los metadatos de la API para obtener el estilo, los parámetros y la URL. Para obtener más información, consulte OpenAPI metadata.

Instalar la biblioteca principal del SDK

Agregue a continuación la dependencia a su archivo pom.xml. Consulte el repositorio de Maven para conocer la versión más reciente.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>tea-openapi</artifactId>
    <version>0.3.10</version>
</dependency>

Invocar una operación de API

Inicializar un cliente de solicitudes

Cree un objeto com.aliyun.teaopenapi.Client para inicializar un cliente de solicitudes. También puede usar la herramienta Credentials para la autenticación. Para obtener más información sobre esta herramienta, consulte Manage credentials.

Nota

El recolector de basura elimina automáticamente el objeto de cliente. No necesita destruirlo de forma manual.

        // 1. Initialize a request client
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Specify the endpoint of ASAPI.
        config.setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
        // Optional. Configure a proxy by using the Config object when you initialize the client. 
        // Specify HTTPS as the protocol when you initialize the client.
        // config.setProtocol("HTTPS");
        // Specify the region ID.
        // config.setRegionId("<regionId>");
        // Configure a proxy when you initialize the client.
        // config.setHttpProxy("http://127.0.0.1:9898");
        // config.setHttpsProxy("http://user:password@127.0.0.1:8989");
        // config.setNoProxy("127.0.0.1,localhost");
        // Configure timeout periods when you initialize the SDK client.
        // The default timeout period for connection requests is 5,000 milliseconds. The value is calculated by using the formula: 5 × 1,000 = 5,000.
        // config.setConnectTimeout(5000);
        // The default timeout period for read requests is 10,000 milliseconds.
        // config.setReadTimeout(10000);
        com.aliyun.teaopenapi.Client client = new com.aliyun.teaopenapi.Client(config);

//        //  Use the Credentials tool
//        com.aliyun.credentials.models.Config credentialConfig = new com.aliyun.credentials.models.Config();
//        credentialConfig.setType("access_key");
//        credentialConfig.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
//        credentialConfig.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
//        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
//        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
//                .setCredential(credentialClient)
//                .setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
//        com.aliyun.teaopenapi.Client client = new com.aliyun.teaopenapi.Client(config);

Configurar los detalles de la operación de API

Use com.aliyun.teaopenapi.models.Params para configurar el estilo de la API, la versión y el método de la solicitud. A continuación se muestra un ejemplo que invoca DescribeInstanceTypeFamilies.

        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                .setStyle("RPC")  // The API style, such as remote procedure call (RPC) or resource-oriented architecture (ROA). 
                .setVersion("2014-05-26") // The API version. 
                .setMethod("POST") // The request method. 
                .setAction("DescribeInstanceTypeFamilies")  // The name of the API operation. 
                .setPathname("/") // The URL of the operation. The default path of an RPC-style operation is /. You can obtain the URL of an ROA-style operation from the data.path parameter in the API metadata. 
                .setProtocol("HTTPS") // The request protocol, such as HTTPS or HTTP. We recommend that you use HTTPS. 
                .setAuthType("AK") // The authentication type. Use the default type. If the operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request. 
                .setReqBodyType("json") // The type of request body. Valid values: byte, json, and formData. 
                .setBodyType("json"); // The response format. JSON is supported.

Configurar los parámetros de la solicitud

Use com.aliyun.teaopenapi.models.OpenApiRequest para pasar los parámetros de la solicitud mediante una cadena de consulta, un cuerpo o un flujo. Elija el método según los metadatos de la API. Por ejemplo, RegionId en DescribeInstanceTypeFamilies se define como {"name":"RegionId","in":"query",...}}, donde "in":"query" indica que se pasa como parámetro de consulta.

Forma de pasar el parámetro

Escenario

setQuery

Los metadatos definen "in":"query". Pase los parámetros en setQuery.

setBody

Los metadatos definen "in":"body'' o "in": "formData". Pase los parámetros en setBody y configure reqBodyType para que coincida con el formato del cuerpo.

setStream

Utilice setStream cuando necesite pasar flujos de archivos para subirlos.

        // Scenario 1: Configure a query string.
        java.util.Map<String, Object> queries = new java.util.HashMap<>();
        queries.put("RegionId", "cn-hangzhou");
        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                .setQuery(com.aliyun.openapiutil.Client.query(queries));

//        // Method 2: Configure the body and set reqBodyType to json.
//        java.util.Map<String, Object> body = new java.util.HashMap<>();
//        body.put("param1", "value1");
//        body.put("param2", "value2");
//        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
//                .setBody(com.aliyun.openapiutil.Client.query(body));

//        // Method 3: Configure the body and set reqBodyType to formData.
//        java.util.Map<String, Object> formData = new java.util.HashMap<>();
//        formData.put("param1", "value1");
//        formData.put("param2", "value2");
//        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
//                .setBody(formData);

//        // Method 4: Configure the Stream parameter to pass file streams
//        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
//                .setStream("<FILE_STREAM>");  // Replace <FILE_STREAM> with the actual file stream.

Enviar la solicitud

Invoque callApi en el objeto com.aliyun.teaopenapi.Client. Puede especificar parámetros de tiempo de ejecución, como los tiempos de espera y los proxy. Para obtener más información, consulte Advanced settings.

        // Configure runtime options.
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// Disable SSL certificate authentication.
//        runtime.ignoreSSL = true;
// Enable the automatic retry mechanism.
//        runtime.autoretry = true;
// Specify the number of automatic retries.
//        runtime.maxAttempts = 3;
// Specify the connection timeout period.
//        runtime.connectTimeout = 5000;
// Specify the timeout period of read requests.
//       runtime.readTimeout = 10000;
        // The response is of the MAP type, which contains the response body, response headers, and HTTP status code. 
        java.util.Map<String, ?> response = client.callApi(params, request, runtime);
        System.out.println(new com.google.gson.Gson().toJson(response));

Ejemplos

Ejemplo: invocar una operación de API con estilo RPC

A continuación se muestra un ejemplo de llamada genérica a la operación DescribeInstanceTypeFamilies de ECS.

import com.aliyun.teaopenapi.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teaopenapi.models.OpenApiRequest;
import com.aliyun.teaopenapi.models.Params;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

import static com.aliyun.openapiutil.Client.query;

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"))
                .setEndpoint("ecs-cn-hangzhou.aliyuncs.com");
        Client client = new Client(config);
        Params params = new Params()
                .setStyle("RPC")  // The API style.
                .setVersion("2014-05-26") // The version number of the operation.
                .setMethod("POST") // The HTTP method of the operation.
                .setAction("DescribeInstanceTypeFamilies")  // The name of the API operation.
                .setPathname("/") 
                .setProtocol("HTTPS")
                .setAuthType("AK")
                .setReqBodyType("json")
                .setBodyType("json");
        // Specify the query parameters.
        Map<String, Object> queries = new HashMap<>();
        queries.put("RegionId", "cn-hangzhou");
        // Create a runtime configuration object.
        RuntimeOptions runtime = new RuntimeOptions();
        OpenApiRequest request = new OpenApiRequest()
                .setQuery(query(queries));
        // The response is of the MAP type, which contains the response body, response headers, and HTTP status code. 
        Map<String, ?> response = client.callApi(params, request, runtime);
        System.out.println(new Gson().toJson(response));
    }
}

Ejemplo: invocar una operación de API con estilo RESTful (ROA)

A continuación se muestra un ejemplo de llamada genérica a la operación DescribeClustersV1 de ACK.

import com.aliyun.teaopenapi.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teaopenapi.models.OpenApiRequest;
import com.aliyun.teaopenapi.models.Params;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

import static com.aliyun.openapiutil.Client.query;

public class Test3 {
    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"))
                .setEndpoint("cs.cn-hangzhou.aliyuncs.com");
        Client client = new Client(config);
        Params params = new Params()
                .setStyle("ROA") // The API style.
                .setVersion("2015-12-15") // The API version.
                .setAction("DescribeClustersV1") // The operation that you want to call.
                .setPathname("/api/v1/clusters") // The API URI.
                .setMethod("GET") // The request method.
                .setProtocol("HTTPS")
                .setAuthType("AK")
                .setReqBodyType("json")
                .setBodyType("json");
        // Specify the query parameters.
        Map<String, Object> queries = new HashMap<>();
        queries.put("name", "cluster-demo");
        OpenApiRequest request = new OpenApiRequest()
                .setQuery(query(queries));
        RuntimeOptions runtime = new RuntimeOptions();
        // The response is of the MAP type, which contains the response body, response headers, and HTTP status code. 
        Map<String, ?> response = client.callApi(params, request, runtime);
        System.out.println(new Gson().toJson(response));
    }
}