Tüm Ürünler
Search
Belge Merkezi

Alibaba Cloud SDK:Generic calls

Son Güncelleme:Oct 07, 2026

Alibaba Cloud SDK for Java V2.0, hizmete özgü SDK'lar yüklemeden herhangi bir OpenAPI işlemini çağırmanıza olanak tanıyan genel API çağrılarını destekler.

Avantajlar

Hafif: Yalnızca SDK çekirdek kitaplığı gereklidir. Hizmete özgü SDK'lara gerek yoktur.

Kullanımı kolay: Ortak istek parametrelerini oluşturun, ortak bir istemci ile çağrı yapın ve yanıtları standart bir biçimde alın.

Daha fazla bilgi için bkz. Genel çağrılar ve özel çağrılar.

Başlamadan önce

Genel bir çağrı yapmadan önce, API stilini, parametreleri ve uç noktayı edinmek için API meta verilerini görüntüleyin. Daha fazla bilgi için bkz. OpenAPI meta verileri.

SDK çekirdek kitaplığını yükleyin

Aşağıdaki bağımlılığı pom.xml dosyanıza ekleyin. En son sürüm için Maven Repository sayfasını kontrol edin.

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

Bir API işlemi çağırma

İstek istemcisini başlatma

İstek istemcisini başlatmak için bir com.aliyun.teaopenapi.Client nesnesi oluşturun. Kimlik doğrulama için Credentials aracını da kullanabilirsiniz. Credentials aracı hakkında daha fazla bilgi için bkz. Kimlik bilgilerini yönetme.

Not

İstemci nesnesi otomatik olarak garbage collection (çöp toplama) işlemine tabi tutulur. Nesneyi manuel olarak yok etmeniz gerekmez.

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

API işlemi ayrıntılarını yapılandırma

API stilini, sürümü ve istek yöntemini yapılandırmak için com.aliyun.teaopenapi.models.Params kullanın. Aşağıdaki örnek DescribeInstanceTypeFamilies işlemini çağırır.

        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.

İstek parametrelerini yapılandırma

İstek parametrelerini bir sorgu dizesi, gövde veya akış aracılığıyla iletmek için com.aliyun.teaopenapi.models.OpenApiRequest kullanın. API meta verilerine göre yöntemi seçin. Örneğin, DescribeInstanceTypeFamilies içindeki RegionId parametresi {"name":"RegionId","in":"query",...}} olarak tanımlanmıştır; burada "in":"query" ifadesi parametrenin bir sorgu parametresi olarak iletildiği anlamına gelir.


Parametrenin iletilme şekli


Senaryo


setQuery


Meta veriler "in":"query" olarak tanımlar. Parametreleri setQuery içinde iletin.


setBody


Meta veriler "in":"body'' veya "in": "formData" olarak tanımlar. Parametreleri setBody içinde iletin ve gövde biçimine uyması için reqBodyType değerini ayarlayın.


setStream


Dosya yüklemeleri için dosya akışlarını iletmek üzere setStream kullanın.

        // 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.

İsteği gönderme

com.aliyun.teaopenapi.Client nesnesinde callApi yöntemini çağırın. Zaman aşımları ve proxy'ler gibi çalışma zamanı parametrelerini belirtebilirsiniz. Daha fazla bilgi için bkz. Gelişmiş ayarlar.

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

Örnekler

Örnek: RPC tarzı bir API işlemi çağırma

Aşağıdaki örnek, ECS DescribeInstanceTypeFamilies işlemine genel bir çağrı yapar.

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

Örnek: RESTful tarzı (ROA tarzı) bir API işlemi çağırma

Aşağıdaki örnek, ACK DescribeClustersV1 işlemine genel bir çağrı yapar.

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