Tüm Ürünler
Search
Belge Merkezi

Alibaba Cloud SDK:Generalized calls

Son Güncelleme:Oct 07, 2026

Alibaba Cloud SDK V1.0 for Java, genel API çağrılarını destekler. Bu konuda, Alibaba Cloud SDK V1.0 for Java kullanılarak genel çağrıların nasıl yapılacağı açıklanmaktadır.

Özellikler

  1. Hafiflik: Tüm OpenAPI'leri çağırmak için ayrı ürün SDK'larını yüklemenize gerek kalmaz; yalnızca aliyun-java-sdk-core paketini yüklemeniz yeterlidir.

  2. Hızlı yineleme ve uyumluluk: Bir cloud hizmeti SDK sağlamıyorsa veya SDK en son API işlemleri için güncellenmemişse genel çağrılar yapabilirsiniz. Bu sayede, SDK güncellemelerini beklemeden en yeni API işlemlerini çağırabilirsiniz.

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

Kullanım notları

Genel bir çağrı yapmadan önce API sürümü, istek URL'si ve parametre türü gibi gerekli meta verileri manuel olarak elde edip belirtin. Daha fazla bilgi için bkz. API meta verileri.

Core SDK'yı Yükleyin

Alibaba Cloud SDK V1.0 for Java'nın core kütüphanesini yüklemek için pom.xml dosyasına aşağıdaki bağımlılığı ekleyin.

<dependency>
     <groupId>com.aliyun</groupId>
     <artifactId>aliyun-java-sdk-core</artifactId>
     // Select a version.
     <version>[(4.0.0,5.0.0)]</version>
</dependency>

API işlemi çağırma

İstek istemcisini başlatma

com.aliyuncs paketinde, istek istemcisini başlatmak için bir client modülü oluşturun ve client kullanarak API operations çağırın. Bu örnekte, istek istemcisini başlatmak için bir AccessKey pair kullanılır. Daha fazla bilgi için bkz. Erişim kimlik bilgilerini yönetme.

Not

AccessKey sızıntılarını önlemek için AccessKey çiftini ortam değişkenlerinde kaydedebilirsiniz. Daha fazla bilgi için bkz. Linux, macOS ve Windows'ta ortam değişkenlerini yapılandırma.

 import com.aliyuncs.DefaultAcsClient;
 import com.aliyuncs.profile.DefaultProfile;
 
        // 1. Create and initialize a DefaultAcsClient instance.
        DefaultProfile profile = DefaultProfile.getProfile(
                // Your region ID.
                "cn-hangzhou",
                // System.getenv indicates that the AccessKey ID of the Resource Access Management (RAM) user is obtained from an environment variable.
                System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // System.getenv indicates that the AccessKey secret of the RAM user is obtained from an environment variable.
                System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Optional. Configure HTTPS for the client.
        HttpClientConfig clientConfig = HttpClientConfig.getDefault();
//        // Do not verify the server-side certificate.
//        clientConfig.setIgnoreSSLCerts(true);
//        // The maximum number of connections for each host.
//        clientConfig.setMaxRequestsPerHost(6);
//        // The connection timeout.
//        clientConfig.setConnectionTimeoutMillis(30000L);
//        // The read timeout.
//        clientConfig.setReadTimeoutMillis(30000L);
//        // The write timeout.
//        clientConfig.setWriteTimeoutMillis(60000L);
//        // Set an HTTP proxy.
//        clientConfig.setHttpProxy("http://127.0.0.1:9898");
//        // Set an HTTPS proxy.
//        clientConfig.setHttpsProxy("http://user:password@127.0.0.1:8989");
//        // Set a list of addresses to ignore for the proxy.
//        clientConfig.setNoProxy("127.0.0.1,localhost");

        profile.setHttpClientConfig(clientConfig);
        IAcsClient client = new DefaultAcsClient(profile);

API işleminin temel bilgilerini ve istek parametrelerini yapılandırma

CommonRequest kullanarak API operation için ortak istek parametrelerini ve işleme özel parametreleri yapılandırın. Ortak istek parametreleri hakkında daha fazla bilgi için bkz. Gelişmiş ayarlar.

Not

CommonRequest modülü, sürüm numarası, URL ve parametre türü gibi API meta verilerini standart bir istek yapılandırma süreci aracılığıyla geçerli bir HTTP isteğine dönüştürür ve ardından orijinal yanıt verilerini döndürür. Parametrelerin nasıl iletileceği, API stiline ve tasarımına bağlıdır.

API İstek Parametreleri

Bir istek parametresinin nasıl iletileceği, API işleminin meta verileri tarafından belirlenir. Örneğin, DescribeInstanceStatus API işlemi, meta verilerde {"name":"RegionId","in":"query",...}} olarak tanımlanmıştır. Bu durumda, "in":"query" ifadesi bölge kimliğinin (RegionId) putQueryParameter ile iletilmesi gerektiğini gösterir.

Açıklama

Parametrenin iletilme şekli

İstek parametresi "in":"query" olarak ayarlandığında geçerlidir.

putQueryParameter(String key,String value)

Not

Bir istek parametresi koleksiyon ise parametreyi putQueryParameter("key.1","value1"); şeklinde belirtebilirsiniz;

Parametreleri putQueryParameter("key.2","value2");... biçiminde iletebilirsiniz.

İstek parametresi "in":"body" veya "in": "formData" olduğunda geçerlidir.

putBodyParameter(String key,String value)

Not

İstek parametresi bir dize belirtmiyorsa parametre değerini JSON dizesine dönüştürün ve dizeyi değişken değeri olarak belirtin. Örnek: request.putBodyParameter("key",new Gson().toJson(value));

Dosya yükleme

setHttpContent(byte[] content,String charset,FormatType formatType)

Not

formatType değerini FormatType.RAW olarak ayarlayın.

        // 2. Create an API request and configure the request parameters.
        // This example shows how to create a request to call the DescribeInstanceStatus operation, which is used to obtain the status of an Elastic Compute Service (ECS).
        CommonRequest request = new CommonRequest();
        // 2.1  Configure the common request parameters.
        request.setSysMethod(com.aliyuncs.http.MethodType.POST);
        request.setSysDomain("ecs-cn-hangzhou.aliyuncs.com");// The domain name of the API operation.
        request.setSysVersion("2014-05-26");// The API version.
        request.setSysAction("DescribeInstanceStatus"); // The name of the API operation. When you call an RPC-style API operation, you must configure SysAction() to specify the name of the API operation.
        request.setSysConnectTimeout(30000); // The timeout period.
        request.setSysProtocol(com.aliyuncs.http.ProtocolType.HTTPS); // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. 
//        request.setSysUriPattern("/"); // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS. Do not configure this parameter for RPC-style API operations. 
        
        // 2.2 Configure operation-specific request parameters.
        // Scenario 1: Specify the query parameters in putQueryParameter(string key,string value).
        request.putQueryParameter("RegionId", "cn-hangzhou");
        List<String> instanceIds = List.of(
                "i-bp1axhql4dqXXXXXXXX",
                "i-bp124uve8zqXXXXXXXX"
        );
        for(int i = 0; i < instanceIds.size(); ++i) {
            request.putQueryParameter("InstanceId." + (i + 1), (String)instanceIds.get(i));
        }
        request.putQueryParameter("PageNumber", "1");
        request.putQueryParameter("PageSize", "30");

        // Scenario 2: Specify the body parameters in putBodyParameter(string key,string value).
        // request.putBodyParameter("key1", "value1");
        // request.putBodyParameter("key2", "value2");
        // request.putBodyParameter("key3", "value3");

        // Scenario 3: To upload files, specify setHttpContent(byte[] content,String charset,FormatType formatType). Set formatType to FormatType.RAW. 
        // byte[] bodyImg = Files.readAllBytes(Paths.get("<FILE_PATH>")); // Replace <FILE_PATH> with the actual file path.
        // request.setHttpContent(bodyImg, "UTF-8", FormatType.RAW);
  

İstek gönderme

client kullanarak getCommonResponse yöntemini çağırın.

// Send the request.
CommonResponse response = client.getCommonResponse(request);
// The return value, response.getData(), is JSON-formatted data that contains the RequestId and the OpenAPI return parameters.
System.out.println(response.getData());

Örnek kod

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

Bu örnekte, ECS'nin DescribeInstanceStatus işlemi CommonRequest kullanılarak çağrılır.

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.GsonBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class Sample {
    public static void main(String[] args) throws ClientException, UnsupportedEncodingException {
        // Create and initialize a DefaultAcsClient instance.
        DefaultProfile profile = DefaultProfile.getProfile(
                // Your region ID.
                "cn-hangzhou",
                // Obtain the AccessKey ID of the RAM user from an environment variable.
                System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Obtain the AccessKey secret of the RAM user from an environment variable.
                System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        IAcsClient client = new DefaultAcsClient(profile);
        
        // Create an API request and set parameters.
        CommonRequest request = new CommonRequest();
        request.setSysMethod(com.aliyuncs.http.MethodType.POST); // The request method.
        request.setSysDomain("ecs-cn-hangzhou.aliyuncs.com"); // The domain name of the API operation.
        request.setSysVersion("2014-05-26"); // The API version number.
        request.setSysAction("DescribeInstanceStatus"); // The name of the API operation. When you call an RPC-style API operation, you must configure SysAction() to specify the operation name.
         request.setSysProtocol(com.aliyuncs.http.ProtocolType.HTTPS); // The request protocol. Valid values: HTTPS and HTTP. We recommend that you use HTTPS.
        request.putQueryParameter("RegionId", "cn-hangzhou");
        List<String> instanceIds = List.of(
                "i-bp1axhql4dqXXXXXXXX",
                "i-bp124uve8zqXXXXXXXX"
        );
        for(int i = 0; i < instanceIds.size(); ++i) {
            request.putQueryParameter("InstanceId." + (i + 1), (String)instanceIds.get(i));
        }
        request.putQueryParameter("PageNumber", "1");
        request.putQueryParameter("PageSize", "30");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

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

Bu örnekte, Container Service for Kubernetes (ACK) hizmetinin DescribeClustersV1 işlemi CommonRequest kullanılarak çağrılır.

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
public class Sample {
    public static void main(String[] args) {
        // Create and initialize a DefaultAcsClient instance.
        DefaultProfile profile = DefaultProfile.getProfile(
                // Your region ID.
                "cn-hangzhou",
                // Obtain the AccessKey ID of the RAM user from an environment variable.
                System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Obtain the AccessKey secret of the RAM user from an environment variable.
                System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        IAcsClient client = new DefaultAcsClient(profile);
        // Create an API request and set parameters.
        CommonRequest request = new CommonRequest();
        request.setSysDomain("cs.aliyuncs.com");// The domain name.
        request.setSysVersion("2015-12-15");// The API version.
        request.setSysUriPattern("/clusters"); // The URI of the API resource. When you call a ROA-style API operation, you must configure UriPattern() to specify the complete resource path. Obtain the resource path from data.path in the OpenAPI metadata.
        request.setSysMethod(MethodType.GET);// The request method.
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

SSS

  1. Hata mesajı, gerekli "AccessKeyId" parametresinin eksik olduğunu gösterir.

    Neden: AccessKey çifti doğru şekilde yapılandırılmamış.

    Çözümler:

    1. ALIBABA_CLOUD_ACCESS_KEY_ID ve ALIBABA_CLOUD_ACCESS_KEY_SECRET ortam değişkenlerinin yapılandırılıp yapılandırılmadığını kontrol etmek için aşağıdaki komutları çalıştırın.

      Linux/macOS

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

      Windows

      echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
      echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

      Geçerli bir AccessKey çifti döndürülüyorsa ortam değişkenleri doğru şekilde yapılandırılmıştır. AccessKey çifti döndürülmez veya geçersiz bir çift döndürülürse ortam değişkenlerini gerektiği gibi yapılandırın. Daha fazla bilgi için bkz. Linux, macOS ve Windows'ta ortam değişkenlerini yapılandırma.

    2. Kodda AccessKey çiftiyle ilgili hataları kontrol edin.

      Yaygın hata örnekleri:

      accessKeyId = System.getenv("yourAccessKeyID"),
      accessKeySecret = System.getenv("yourAccessKeySecret")
      Not

      Yukarıdaki örnek hatalı istekte, System.getenv() giriş değerleri AccessKey çifti olarak kullanılmıştır. Ancak bu işlev, değerleri ortam değişkenlerinden okumak için kullanılır. Makinenizde ortam değişkeni adlarını ALIBABA_CLOUD_ACCESS_KEY_ID ve ALIBABA_CLOUD_ACCESS_KEY_SECRET olarak belirttiğinizde System.getenv değerleri ortam değişkenlerinden okuyabilir.

      Doğru örnek

      System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
  2. İstek şu hata mesajıyla başarısız olur: "com.aliyuncs.exceptions.ClientException: MissingParameter : The input parameter "Timestamp" that is mandatory for processing this request is not supplied."

    Neden: RPC tarzı API işleminin ortak istek parametrelerinde SysUriPattern parametresi yapılandırılmış.

    Çözüm: Ortak istek parametrelerinden SysUriPattern parametresini kaldırın.