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 a necessidade de instalar SDKs específicos para cada 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 individualmente.

Facilidade de uso: construa um objeto de parâmetros de solicitação comum, utilize um cliente genérico para enviar a solicitação e receba respostas em um formato padronizado.

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

Notas de uso

Antes de realizar 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 a biblioteca principal do Alibaba Cloud SDK V2.0 for Go

Execute o comando a seguir para instalar a biblioteca principal:

go get github.com/alibabacloud-go/darabonba-openapi/v2/client

Invoque uma operação de API

Inicialize um cliente de solicitação

Crie um objeto darabonba-openapi/v2/client para inicializar o cliente de solicitação. Também é possível usar a ferramenta Credentials para essa finalidade. Para mais detalhes, consulte Gerenciar credenciais de acesso.

import (
	"fmt"
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
)

        // os.Getenv indicates that the AccessKey ID and AccessKey secret are obtained from environment variables.
	config := &openapi.Config{
	 	AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// Specify the endpoint of the service.
	config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
	// Initialize and return the client.
	client, err := openapi.NewClient(config)
	if err != nil {
		panic(err)
	 }

	// Use the default credential to initialize the client. 
	// credentialClient, _err := credentials.NewCredential(nil)
	// if _err != nil {
	//	panic(_err)
	// }
	// config := &openapi.Config{
	//	Credential: credentialClient,
	// }
	// config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
	// client, err := openapi.NewClient(config)
	// if err != nil {
	//	panic(_err)
	// }

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

Utilize openapi.Params para configurar a operação de API, incluindo o estilo, a versão e o método de solicitação. O exemplo a seguir invoca a operação DescribeInstanceTypeFamilies.

        // Configure the basic information about the API operation.
        params := &openapi.Params{
		// Specify the required parameters such as Action and Version for the API operation.
		Action:      tea.String("DescribeInstanceTypeFamilies"), // The API operation.
		Version:     tea.String("2014-05-26"), // The version number of the API operation.
		Protocol:    tea.String("HTTPS"), // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. 
		Method:      tea.String("POST"), // The request method.
		AuthType:    tea.String("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:       tea.String("RPC"), // The API style, such as remote procedure call (RPC) and resource-oriented architecture (ROA). 
		Pathname:    tea.String("/"), // 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: tea.String("json"), // The type of request body. Valid values: byte, json, and formData. 
		BodyType:    tea.String("json"), // The response format. Valid value: json. 
	}

Configure os parâmetros de solicitação

Use openapi.OpenApiRequest para definir os parâmetros de solicitação. A transmissão dos dados pode ocorrer via query string, corpo da solicitação ou stream. Escolha o método adequado com base nos metadados da API. Por exemplo, o parâmetro RegionId da operação DescribeInstanceTypeFamilies aparece como {"name":"RegionId","in":"query",...}} nos metadados. O atributo "in":"query" indica que o RegionId deve ser enviado na query string.

Forma de envio do parâmetro

Descrição

Query

Quando os metadados definem "in":"query", envie o parâmetro na query string.

Body

Caso os metadados especifiquem "in":"body'' ou "in": "formData", transmita o parâmetro no corpo da solicitação. Ao enviar parâmetros dessa forma, defina um valor para reqBodyType conforme o tipo de corpo utilizado.

Stream

Para upload de arquivos, configure o parâmetro Stream a fim de transmitir fluxos de arquivo.

        // Scenario 1: Configure a query string.
	query := map[string]interface{}{
		"RegionId": tea.String("cn-hangzhou"),
	}
	// Create a request and configure the required parameters.
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(query),
	}

	// Scenario 2: Configure a body and set reqBodyType to json.
	// reqBody := map[string]interface{}{
	// 	"param1": tea.String("value1"),
	//      "param2": tea.String("value2"),
	// }
	// // Create an API request and set the required parameters.
	// request := &openapi.OpenApiRequest{
	// 	Body: openapiutil.Query(reqBody),
	// }

	// Scenario 3: Configure a body and set reqBodyType to formData.
	// reqForm := map[string]interface{}{
	// 	"param1": tea.String("value1"),
	//      "param2": tea.String("value2"),
	// }
	// request := &openapi.OpenApiRequest{
	// 	// Convert the form parameters to a URL-encoded string.
	// 	Body: reqForm,
	// }

	// Scenario 4: Use the Stream parameter to pass file streams
	// request := &openapi.OpenApiRequest{
	// 	Stream: '<FILE_STREAM>', // Replace <FILE_STREAM> with the file stream that you want to pass.
	// }

Envie a solicitação

Invoque a função CallApi no objeto client para enviar a solicitação. É possível especificar parâmetros de tempo de execução, como timeouts e proxies. Para mais informações, consulte Configurações avançadas.

        // Configure runtime options.
	runtime := &util.RuntimeOptions{}
	// Ignore SSL certificate-related errors.
        // runtime.IgnoreSSL = tea.Bool(true)
        // Configure a proxy by using RuntimeOptions.
	// runtime.HttpProxy = tea.String("http://127.0.0.1:9898")
	// runtime.HttpsProxy = tea.String("http://user:password@127.0.0.1:8989")
	// runtime.NoProxy = tea.String("127.0.0.1,localhost")
	// Configure timeout periods. Unit: milliseconds.
	// runtime.ConnectTimeout = tea.Int(10000) // Set the timeout period for connection requests to 10 seconds.
	// runtime.ReadTimeout = tea.Int(10000) // Set the timeout period for read requests to 10 seconds.
	// Call the API operation and return the response.
	response, err := client.CallApi(params, request, runtime)
	if err != nil {
		panic(err)
	}
	// The response is of the MAP type, which contains the response body, response headers, and HTTP status code. 
	fmt.Println(response["body"])

Código de exemplo

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

O exemplo abaixo realiza uma chamada genérica para a operação DescribeInstanceTypeFamilies do ECS.

package main

import (
	"fmt"
	"os"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	openapiutil "github.com/alibabacloud-go/openapi-util/service"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

func main() {
	// Obtain the AccessKey ID and AccessKey secret from environment variables.
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// Specify the endpoint of the service.
	config.Endpoint = tea.String("ecs-cn-hangzhou.aliyuncs.com")
	// Initialize and return the client.
	client, err := openapi.NewClient(config)
	if err != nil {
		panic(err)
	}
	params := &openapi.Params{
		// Specify the required parameters such as Action and Version for the API operation.
		Action:      tea.String("DescribeInstanceTypeFamilies"), // The API operation.
		Version:     tea.String("2014-05-26"), // The version number of the API operation.
		Protocol:    tea.String("HTTPS"), // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. 
		Method:      tea.String("POST"), // The request method.
		AuthType:    tea.String("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:       tea.String("RPC"), // The API style, such as RPC and ROA.
		Pathname:    tea.String("/"), // The path of the API operation. The default path of RPC-style API operations is /.
		ReqBodyType: tea.String("json"), // The format of the request body. 
		BodyType:    tea.String("json"), // The format of the response body. 
	}

	// Configure the query parameters.
	query := map[string]interface{}{
		"RegionId": tea.String("cn-hangzhou"),
	}
	// Configure the runtime options.
	runtime := &util.RuntimeOptions{}
	// Create an API request and configure the parameters.
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(query),
	}
	// Call the API operation and return the response.
	response, err := client.CallApi(params, request, runtime)
	if err != nil {
		panic(err)
	}
	// The response is of the MAP type, which contains the response body, response headers, and HTTP status code. 
	fmt.Println(response["body"])
}

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

Este exemplo demonstra uma chamada genérica para a operação DescribeClustersV1 do ACK.

package main

import (
	"fmt"
	"os"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	openapiutil "github.com/alibabacloud-go/openapi-util/service"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

func main() {
	// Obtain the AccessKey ID and AccessKey secret from environment variables.
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// Specify the endpoint of the service. For more information, visit https://api.alibabacloud.com/product/CS.
	config.Endpoint = tea.String("cs.cn-qingdao.aliyuncs.com")
	client, err := openapi.NewClient(config)
	if err != nil {
		panic(err)
	}
	params := &openapi.Params{
		// The operation that you want to call.
		Action: tea.String("DescribeClustersV1"),
		// The version number of the API operation.
		Version: tea.String("2015-12-15"),
		// The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. 
		Protocol: tea.String("HTTPS"),
		// The HTTP method of the API operation.
		Method:   tea.String("GET"),
		// 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. 
		AuthType: tea.String("AK"),
		// API style, such as RPC and ROA.
		Style:    tea.String("ROA"),
		// 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. 
		Pathname: tea.String("/api/v1/clusters"),
		// The format of the request body.
		ReqBodyType: tea.String("json"),
		// The format of the response body.
		BodyType: tea.String("json"),
	}
	// Configure the query parameters.
	queries := map[string]interface{}{}
	queries["name"] = tea.String("cluster-demo")
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(queries),
	}
	// runtime options
	runtime := &util.RuntimeOptions{}
	// The response is of the MAP type, which contains the response body, response headers, and HTTP status code. 
	response, err := client.CallApi(params, request, runtime)
	if err != nil {
		panic(err)
	}
	fmt.Println(response["body"])
}