O Alibaba Cloud SDK for Java V2.0 oferece suporte a chamadas de API genéricas. Esse recurso permite invocar qualquer operação da OpenAPI sem instalar SDKs específicos para cada serviço.
Benefícios
Leveza: Apenas a biblioteca principal do SDK é necessária. Não há necessidade de SDKs específicos de serviço.
Facilidade de uso: Construa parâmetros de solicitação comuns, use um cliente genérico e receba respostas em formato padrão.
Para mais informações, consulte Chamadas genéricas e chamadas especializadas.
Antes de começar
Antes de fazer uma chamada genérica, visualize os metadados da API para obter o estilo, os parâmetros e a URL. Para mais informações, consulte Metadados da OpenAPI.
Instale a biblioteca principal do SDK
Adicione a seguinte dependência ao arquivo pom.xml. Verifique a versão mais recente no Repositório Maven.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-openapi</artifactId>
<version>0.3.10</version>
</dependency>
Invoque uma operação de API
Inicialize um cliente de solicitação
Crie um objeto com.aliyun.teaopenapi.Client para inicializar um cliente de solicitação. Você também pode usar a ferramenta Credentials para autenticação. Para mais detalhes sobre essa ferramenta, consulte Gerenciar credenciais.
O coletor de lixo remove automaticamente o objeto cliente. Não é necessário destruí-lo manualmente.
// 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);
Configure os detalhes da operação de API
Use com.aliyun.teaopenapi.models.Params para definir o estilo da API, a versão e o método de solicitação. O exemplo abaixo invoca a operação 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.
Configure os parâmetros da solicitação
Use com.aliyun.teaopenapi.models.OpenApiRequest para transmitir parâmetros de solicitação via query string, corpo ou stream. Escolha o método com base nos metadados da API. Por exemplo, o parâmetro RegionId em DescribeInstanceTypeFamilies é definido como {"name":"RegionId","in":"query",...}}, em que "in":"query" indica transmissão como parâmetro de consulta.
|
Forma de transmissão do parâmetro |
Cenário |
|
setQuery |
Os metadados definem |
|
setBody |
Os metadados especificam |
|
setStream |
Use setStream para enviar streams de arquivos durante uploads. |
// 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.
Envie a solicitação
Invoque o método callApi no objeto com.aliyun.teaopenapi.Client. Especifique parâmetros de tempo de execução, como timeouts e proxies. Para mais informações, consulte Configurações avançadas.
// 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));
Exemplos
Exemplo: Invoque uma operação de API no estilo RPC
O exemplo a seguir faz uma chamada genérica para a operação DescribeInstanceTypeFamilies do 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));
}
}
Exemplo: Invoque uma operação de API no estilo RESTful (ROA)
Este exemplo demonstra uma chamada genérica para a operação DescribeClustersV1 do 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));
}
}