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 admite llamadas genéricas a la API, las cuales le permiten invocar cualquier operación de openapi sin instalar los SDK específicos de cada servicio.

Características

Ligero: solo se requiere la biblioteca principal de Alibaba Cloud SDK. No es necesario instalar el SDK de cada servicio.

Fácil de usar: construya los parámetros comunes de la solicitud, use un cliente común para enviar las solicitudes y reciba respuestas en formatos estándar.

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

Notas de uso

Antes de ejecutar una llamada genérica, consulte los metadata of the API operation para obtener el estilo de la API, los parámetros de la solicitud y la URL.

Instalar el SDK

Ejecute el siguiente comando para instalar la biblioteca principal de Alibaba Cloud SDK V2.0 para .NET. Para consultar la versión más reciente, visite AlibabaCloud.OpenApiClient.

dotnet add package AlibabaCloud.OpenApiClient --version 0.1.13

Invocar una operación de la API

Inicializar un cliente de solicitud

Cree un objeto AlibabaCloud.OpenApiClient.Client para inicializar un cliente de solicitud. También puede usar la herramienta Credentials para gestionar las credenciales. Para obtener más información, consulte Managing access credentials.

        public static AlibabaCloud.OpenApiClient.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config =
                new AlibabaCloud.OpenApiClient.Models.Config
                {
                    // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
                    AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                    // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
                    AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                };
            config.Endpoint = "ecs-cn-hangzhou.aliyuncs.com";
            return new AlibabaCloud.OpenApiClient.Client(config);
        }
        
        // Use the Credentials tool.
        // public static AlibabaCloud.OpenApiClient.Client CreateClient()
        // {
        //     // Use an AccessKey pair to initialize the Credentials client. 
        //     Aliyun.Credentials.Models.Config credentialsConfig =
        //         new Aliyun.Credentials.Models.Config()
        //         {
        //             // The credential type. 
        //             Type = "access_key",
        //             // Obtain the AccessKey ID from the environment variable. 
        //             AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
        //             // Obtain the AccessKey secret from the environment variable. 
        //             AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
        //         };
        //     Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
        //     AlibabaCloud.OpenApiClient.Models.Config config =
        //         new AlibabaCloud.OpenApiClient.Models.Config
        //         {
        //             Credential = credentialClient,
        //             Endpoint = "ecs-cn-hangzhou.aliyuncs.com",
        //         };

        //     return new AlibabaCloud.OpenApiClient.Client(config);
        // }

Configurar la información de la operación de la API

Use AlibabaCloud.OpenApiClient.Models.Params para especificar el estilo de la API, la versión y el método de la solicitud. El siguiente ejemplo invoca la operación DescribeInstanceTypeFamilies.

        AlibabaCloud.OpenApiClient.Models.Params params_ =
            new AlibabaCloud.OpenApiClient.Models.Params
            {
                Action = "DescribeInstanceTypeFamilies", // The API operation. 
                Version = "2014-05-26", // The version number of the API operation. 
                Protocol = "HTTPS", // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. 
                Method = "POST", // The request method. 
                AuthType = "AK", // The authentication type. Use the default type. If the API operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request. 
                Style = "RPC", // The API style, such as remote procedure call (RPC) and resource-oriented architecture (ROA). 
                Pathname = "/", // The URL of the API 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. 
                ReqBodyType = "json", // The type of request body. Valid values: json and formData. 
                BodyType = "json", // The response format. Valid value: json. 
            };

Configurar los parámetros de la solicitud

Use AlibabaCloud.OpenApiClient.Models.OpenApiRequest para configurar los parámetros de la solicitud. Según los metadatos de la API, puede pasar los parámetros en una cadena de consulta, en el cuerpo o en un flujo. Por ejemplo, el parámetro RegionId de la operación DescribeInstanceTypeFamilies se define como {"name":"RegionId","in":"query",...}} en los metadatos. El valor "in":"query" indica que RegionId se pasa en una cadena de consulta.

Método

Descripción

Query

Pase el parámetro en la cadena de consulta cuando los metadatos definan "in":"query".

Body

Pase el parámetro en el cuerpo de la solicitud cuando los metadatos definan "in":"body'' o "in": "formData". Especifique un valor para reqBodyType según el tipo de cuerpo de la solicitud.

Stream

Pase flujos de archivos al configurar el parámetro Stream cuando necesite cargar archivos.

        // Method 1: Configure a query string.
        Dictionary<string, object> queries = new Dictionary<string, object>() { };
        queries["RegionId"] = "cn-hangzhou";
        AlibabaCloud.OpenApiClient.Models.OpenApiRequest request =
            new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
            {
                Query = AlibabaCloud.OpenApiUtil.Client.Query(queries),
            };

//        // Method 2: Configure the body and set reqBodyType to json.
//        Dictionary<string, object> body = new Dictionary<string, object>()
//        {
//            { "param1", "value1" },
//            { "param2", "value2" },
//        };
//        AlibabaCloud.OpenApiClient.Models.OpenApiRequest request =
//            new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
//            {
//                Body = AlibabaCloud.OpenApiUtil.Client.Query(body),
//            };

//        // Method 3: Configure the body and set reqBodyType to formData.
//        Dictionary<string, object> formData = new Dictionary<string, object>()
//        {
//            { "param1", "value1" },
//            { "param2", "value2" },
//        };
//        AlibabaCloud.OpenApiClient.Models.OpenApiRequest request =
//            new AlibabaCloud.OpenApiClient.Models.OpenApiRequest { Body = formData };

//        // Method 4: Configure the Stream parameter to pass file streams
//        AlibabaCloud.OpenApiClient.Models.OpenApiRequest request =
//            new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
//            {
//                Stream = "<FILE_STREAM>",
//            };

Enviar una solicitud

Use AlibabaCloud.OpenApiClient.Client para enviar una solicitud mediante la invocación del método CallApi. También puede configurar parámetros de tiempo de ejecución, como los tiempos de espera y la configuración del proxy. Para obtener más información, consulte Advanced configuration.

AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
var response = client.CallApi(params_, request, runtime);
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
Console.WriteLine(response["statusCode"]);

Código de ejemplo

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

El siguiente ejemplo invoca la operación DescribeInstanceTypeFamilies de Elastic Compute Service (ECS) para demostrar una llamada genérica.

namespace AlibabaCloud.SDK.Sample
{
    public class Sample 
    {

        public static AlibabaCloud.OpenApiClient.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
            config.Endpoint = "ecs-cn-hangzhou.aliyuncs.com";
            return new AlibabaCloud.OpenApiClient.Client(config);
        }

        public static AlibabaCloud.OpenApiClient.Models.Params CreateApiInfo()
        {
            AlibabaCloud.OpenApiClient.Models.Params params_ = new AlibabaCloud.OpenApiClient.Models.Params
            {
                // The name of the API operation.
                Action = "DescribeInstanceTypeFamilies",
                // The version number of the API operation.
                Version = "2014-05-26",
                // The protocol of the API operation.
                Protocol = "HTTPS",
                // The HTTP method of the API operation.
                Method = "POST",
                AuthType = "AK",
                Style = "RPC",
                // The path of the API operation.
                Pathname = "/",
                // The format of the request body.
                ReqBodyType = "json",
                // The format of the response body.
                BodyType = "json",
            };
            return params_;
        }

        public static void Main(string[] args)
        {
            AlibabaCloud.OpenApiClient.Client client = CreateClient();
            AlibabaCloud.OpenApiClient.Models.Params params_ = CreateApiInfo();
            // query params
            Dictionary<string, object> queries = new Dictionary<string, object>(){};
            queries["RegionId"] = "cn-hangzhou";
            // runtime options
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            AlibabaCloud.OpenApiClient.Models.OpenApiRequest request = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
            {
                Query = AlibabaCloud.OpenApiUtil.Client.Query(queries),
            };
            // If you copy and run the sample code, write your code to display the response of the operation.
            // The response is of the MAP type, which contains the response body, response headers, and HTTP status code. 
            var response = client.CallApi(params_, request, runtime);
            Console.WriteLine(response["statusCode"]);
        }
    }
}

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

El siguiente ejemplo ejecuta una llamada genérica a la operación DescribeClustersV1 de ACK.

namespace AlibabaCloud.SDK.Sample
{
    public class Sample 
    {

        public static AlibabaCloud.OpenApiClient.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. 
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
            config.Endpoint = "cs.cn-hangzhou.aliyuncs.com";
            return new AlibabaCloud.OpenApiClient.Client(config);
        }

        public static AlibabaCloud.OpenApiClient.Models.Params CreateApiInfo()
        {
            AlibabaCloud.OpenApiClient.Models.Params params_ = new AlibabaCloud.OpenApiClient.Models.Params
            {
                // The name of the API operation.
                Action = "DescribeClustersV1",
                // The version number of the API operation.
                Version = "2015-12-15",
                // The protocol of the API operation.
                Protocol = "HTTPS",
                // The HTTP method of the API operation.
                Method = "GET",
                AuthType = "AK",
                Style = "ROA",
                // The path of the API operation.
                Pathname = "/api/v1/clusters",
                // The format of the request body.
                ReqBodyType = "json",
                // The format of the response body.
                BodyType = "json",
            };
            return params_;
        }

        public static void Main(string[] args)
        {
            AlibabaCloud.OpenApiClient.Client client = CreateClient();
            AlibabaCloud.OpenApiClient.Models.Params params_ = CreateApiInfo();
            // runtime options
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            AlibabaCloud.OpenApiClient.Models.OpenApiRequest request = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest();
            // Write your code to display the response of the operation if necessary.
            // The response is of the MAP type, which contains the response body, response headers, and HTTP status code. 
            var response = client.CallApi(params_, request, runtime);
            Console.WriteLine(response["statusCode"]);
        }
    }
}