Todos os produtos
Search
Central de documentação

Alibaba Cloud SDK:Chamadas genéricas

Última atualização: Jun 28, 2026

O Alibaba Cloud SDK for Java V2.0 oferece suporte a chamadas de API genéricas. Esse recurso permite invocar qualquer operação OpenAPI sem instalar SDKs específicos de serviço.

Características

Leveza: Apenas a biblioteca principal do Alibaba Cloud SDK é necessária. Não é preciso instalar o SDK de cada serviço.

Facilidade de uso: Construa parâmetros de solicitação comuns, use um cliente genérico para iniciar solicitações e receba respostas em formatos padronizados.

Para mais informações, consulte Chamadas genéricas e chamadas especializadas.

Notas de uso

Antes de fazer uma chamada genérica, visualize os metadados da operação de API para obter o estilo da API, os parâmetros de solicitação e a URL.

Instale o SDK

Execute o comando a seguir para instalar a biblioteca principal do Alibaba Cloud SDK V2.0 para .NET. Para obter a versão mais recente, consulte AlibabaCloud.OpenApiClient.

dotnet add package AlibabaCloud.OpenApiClient --version 0.1.13

Chamar uma operação de API

Inicializar um cliente de solicitação

Crie um objeto AlibabaCloud.OpenApiClient.Client para inicializar um cliente de solicitação. Você também pode usar a ferramenta Credentials para gerenciar credenciais. Para mais informações, consulte Gerenciando credenciais de acesso.

        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);
        // }

Configure as informações da operação de API

Use AlibabaCloud.OpenApiClient.Models.Params para especificar o estilo da API, a versão e o método de solicitação. O exemplo a seguir chama a operação 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. 
            };

Configure parâmetros de solicitação

Use AlibabaCloud.OpenApiClient.Models.OpenApiRequest para configurar os parâmetros da solicitação. Passe parâmetros em uma query string, no corpo ou em um stream, conforme os metadados da API. Por exemplo, o parâmetro RegionId da operação DescribeInstanceTypeFamilies está definido como {"name":"RegionId","in":"query",...}} nos metadados. A definição "in":"query" indica que RegionId deve ser passado na query string.

Método

Descrição

Query

Passe o parâmetro na query string quando os metadados definirem "in":"query".

Body

Inclua o parâmetro no corpo da solicitação se os metadados indicarem "in":"body'' ou "in": "formData". Defina um valor para reqBodyType de acordo com o tipo de corpo da solicitação.

Stream

Transmita streams de arquivos configurando o parâmetro Stream quando precisar enviar arquivos.

        // 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>",
//            };

Iniciar uma solicitação

Use AlibabaCloud.OpenApiClient.Client para iniciar uma solicitação chamando o método CallApi. Configure também parâmetros de tempo de execução, como timeout e definições de proxy. Para mais detalhes, consulte Configuração avançada.

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 exemplo

Exemplo: Chamar uma operação de API estilo RPC

O exemplo a seguir chama a operação DescribeInstanceTypeFamilies do Elastic Compute Service (ECS) para demonstrar uma chamada 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"]);
        }
    }
}

Exemplo: Chamar uma operação de API estilo RESTful (ROA)

Este exemplo faz uma chamada genérica para a operação DescribeClustersV1 do 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"]);
        }
    }
}