Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:Initialization (Android SDK)

Son Güncelleme:Oct 01, 2026

OSSClient, OSS hizmeti için Android istemcisidir. Paketleri ve nesneleri yönetmek için yöntemler sağlar. Yazılım geliştirme setini (SDK) kullanarak OSS'ye istek göndermeden önce bir OSSClient örneğini başlatmanız ve ayarlarını yapılandırmanız gerekir.

Not

OSSClient yaşam döngüsü, uygulamanın yaşam döngüsüyle eşleşmelidir. Uygulama başladığında genel bir OSSClient oluşturun ve uygulama sonlandığında OSSClient'i yok edin.

OSSClient'i Başlatın

Önemli

Mobil terminal, güvenilir olmayan bir ortamdır. İstekleri imzalamak amacıyla AccessKeyId ve AccessKeySecret değerlerini doğrudan terminalde saklamak yüksek bir güvenlik tehdidi oluşturur. Güvenlik Belirteci Hizmeti (STS) kimlik doğrulama modunu veya kendi kendine imzalama modunu kullanmanızı öneririz.

Geçici STS kimlik bilgileri bile mobil istemciye ulaştıktan sonra çıkarılabilir; bu nedenle, bunları tek bir kullanıcıya yönelik izinleri kısıtlayan bir RAM ilkesi ve kısa bir geçerlilik süresi ile daha da sınırlandırmalısınız. Kimlik kartları, yüz görüntüleri veya ödeme kimlik bilgileri gibi gizlilik açısından hassas verileri içeren senaryolarda, mobil uygulamanın kullanması üzere önceden imzalanmış bir URL oluşturmak için uygulama sunucunuzu kullanın — mobil uygulamanın kendisi asla bir kimlik bilgisi tutmaz. Kimlik bilgisi sağlayıcısı seçimi için bkz. Erişim kimlik bilgilerini yapılandırma (Android SDK). Önceden imzalanmış URL'ler için bkz. Erişimi yetkilendirme (Android SDK).

Bir OSSClient'i aşağıdaki yollardan biriyle oluşturabilirsiniz.

Not

Yüklemeler ve indirmeler gibi işlemler için arayüzlerin nasıl çağrılacağını öğrenmek için bkz. Hızlı Başlangıç (Android SDK).

Paketleri listelemeye yönelik OSSClient başlatma yöntemi, bu örneklerde gösterilen genel yöntemden farklıdır. Daha fazla bilgi için bkz. Paketleri listeleme (Android SDK).

STS kullanarak bir OSSClient oluşturun

Aşağıdaki kod, STS kullanarak bir OSSClient'in nasıl oluşturulacağını gösterir.

// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Özel bir etki alanı adı kullanarak bir OSSClient oluşturun

Aşağıdaki kod, özel bir etki alanı adı kullanarak bir OSSClient'in nasıl oluşturulacağını gösterir.

// Set yourEndpoint to the custom domain name.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Apsara Stack veya özel etki alanı ortamında bir OSSClient oluşturun

Aşağıdaki kod, Apsara Stack veya özel etki alanı ortamında bir OSSClient'in nasıl oluşturulacağını gösterir.

// Set yourEndpoint to the Endpoint of the region where the bucket is located.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration configuration = new ClientConfiguration();
// Skip CNAME parsing.
List<String> excludeList = new ArrayList<>();
excludeList.add(endpoint);
configuration.setCustomCnameExcludeList(excludeList);
// Create an OSSClient instance.
configuration.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

OSSClient'i Yapılandırın

ClientConfiguration, OSSClient için yapılandırma sınıfıdır. Proxy, bağlantı zaman aşımı ve maksimum bağlantı sayısı gibi parametreleri yapılandırmak için bu sınıfı kullanabilirsiniz.

Parametre

Açıklama

Yöntem

maxConcurrentRequest

Maksimum eşzamanlı istek sayısı. Varsayılan değer: 5.

ClientConfiguration.setMaxConcurrentRequest

socketTimeout

Soket katmanındaki veri iletimi için zaman aşımı süresi (milisaniye cinsinden). Varsayılan değer: 60000.

ClientConfiguration.setSocketTimeout

connectionTimeout

Bağlantı kurma zaman aşımı süresi (milisaniye cinsinden). Varsayılan değer: 60000.

ClientConfiguration.setConnectionTimeout

max_log_size

Günlük dosyasının boyutu. Varsayılan değer: 5 MB.

ClientConfiguration.setMaxLogSize

maxErrorRetry

Bir istek başarısız olduktan sonraki maksimum yeniden deneme sayısı. Varsayılan değer: 2.

ClientConfiguration.setMaxErrorRetry

customCnameExcludeList

Listedeki öğeler, standart ad (CNAME) çözümlemesini atlar.

ClientConfiguration.setCustomCnameExcludeList

proxyHost

Proxy sunucusunun ana bilgisayar adresi.

ClientConfiguration.setProxyHost

proxyPort

Proxy sunucusunun bağlantı noktası.

ClientConfiguration.setProxyPort

mUserAgentMark

Kullanıcı aracısındaki HTTP User-Agent üstbilgisi.

ClientConfiguration.setUserAgentMark

httpDnsEnable

HTTPDNS'nin etkinleştirilip etkinleştirilmeyeceğini belirtir.

  • true: 2.9.12'den önceki sürümler için HTTPDNS varsayılan olarak etkindir.

  • false: 2.9.12 ve sonraki sürümler için HTTPDNS varsayılan olarak devre dışı bırakılmıştır.

ClientConfiguration.setHttpDnsEnable

checkCRC64

64 bitlik döngüsel yinelenen sağlama (CRC-64) özelliğinin etkinleştirilip etkinleştirilmeyeceğini belirtir. Geçerli değerler:

  • true: CRC-64'ü etkinleştirir.

  • false (varsayılan): CRC-64'ü devre dışı bırakır.

ClientConfiguration.setCheckCRC64

followRedirectsEnable

HTTP yönlendirmesinin etkinleştirilip etkinleştirilmeyeceğini belirtir. Geçerli değerler:

  • true: HTTP yönlendirmesini etkinleştirir.

  • false (varsayılan): HTTP yönlendirmesini devre dışı bırakır.

ClientConfiguration.setFollowRedirectsEnable

okHttpClient

Özel bir okHttpClient.

ClientConfiguration.setOkHttpClient

Aşağıdaki kod, OSSClient parametrelerini yapılandırmak için ClientConfiguration'ın nasıl kullanılacağını gösterir.

// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";

ClientConfiguration configuration = new ClientConfiguration();
// Set the maximum number of concurrent requests. Default value: 5.
// configuration.setMaxConcurrentRequest(3);
// Set the timeout period for data transmission at the socket layer. Default value: 60s.
// configuration.setSocketTimeout(50000);
// Set the timeout period for establishing a connection. Default value: 60s.
// configuration.setConnectionTimeout(50000);
// Set the size of the log file. Default value: 5 MB.
// configuration.setMaxLogSize(3 * 1024 * 1024);
// Set the maximum number of retries after a request fails. Default value: 2.
// configuration.setMaxErrorRetry(3);
// Elements in the list will skip CNAME parsing.
// List<String> cnameExcludeList = new ArrayList<>();
// cnameExcludeList.add("cname");
// configuration.setCustomCnameExcludeList(cnameExcludeList);
// The host address of the proxy server.
// configuration.setProxyHost("yourProxyHost");
// The port of the proxy server.
// configuration.setProxyPort(8080);
// The User-Agent header of HTTP in the user agent.
// configuration.setUserAgentMark("yourUserAgent");
// Specifies whether to enable cyclic redundancy check (CRC). Default value: false.
// configuration.setCheckCRC64(true);
// Specifies whether to enable HTTP redirection. Default value: false.
// configuration.setFollowRedirectsEnable(true);
// Set a custom OkHttpClient.
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// configuration.setOkHttpClient(builder.build());

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
configuration.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

Günlük kaydı özelliğini etkinleştirin

Mobil terminal ortamı karmaşıktır. OSS SDK, bazı bölgelerde veya belirli dönemlerde doğru çalışmayabilir. Geliştiricilerin sorunları tespit etmesine yardımcı olmak için, günlük kaydı özelliği etkinleştirildikten sonra OSS SDK günlük bilgilerini yerel olarak kaydeder. Günlük kaydını etkinleştirmek için, OSSClient'i kullanmadan önce bunu başlatmanız gerekir. Yöntemi aşağıdaki gibi çağırın.

// Log style.
// Call OSSLog.enableLog() to enable viewing logs in the console.
// You can write log files to the \OSSLog\logs.csv path on the phone's built-in SD card. This is disabled by default.
// Logs record request data, response data, and exception information for OSS operations.
// For example, requestId and response header.
// The following is a sample log record.
// Android version.
// android_version: 5.1  
// Android phone model.
// mobile_model: XT1085
// Network status.  
// network_state: connected
// Network connection type.
// network_type: WIFI 
// Specific operation behavior information.
// [2017-09-05 16:54:52] - Encounter local execpiton: //java.lang.IllegalArgumentException: The bucket name is invalid. 
// A bucket name must: 
// 1) be comprised of lower-case characters, numbers or dash(-); 
// 2) start with lower case or numbers; 
// 3) be between 3-63 characters long. 
//------>end of log
// Call this method to enable logging.
OSSLog.enableLog();              
Not

Dosyaları sunucunuza yükleyebilir veya günlük dosyalarını yüklemek için Alibaba Cloud Simple Log Service'i kullanabilirsiniz.

Senkron ve asenkron arayüzler

Android SDK, yükleme ve indirme arayüzleri için hem senkron hem de asenkron çağrı örnekleri sağlar. Bunun nedeni, mobil uygulama geliştirmede ağ isteklerinin UI iş parçacığında izin verilmemesidir. Diğer arayüzler için asenkron çağrı örnekleri temel örneklerdir.

  • Senkron çağrı

    • Senkron bir arayüz çağrısı, bir sonuç dönene kadar iş parçacığını engeller.

    • Senkron arayüzleri UI iş parçacığında çağırmayın.

    • Senkron bir arayüz çağrısı sırasında bir özel durum oluştuğunda, doğrudan bir ClientException veya ServiceException oluşturulur. ClientException, ağ bağlantısı sorunu veya geçersiz bir parametre gibi yerel bir özel durumu belirtir. ServiceException ise kimlik doğrulama hatası veya sunucu hatası gibi OSS tarafından döndürülen bir hizmet hatasını belirtir.

  • Asenkron çağrı

    • Asenkron bir arayüz için, istek yaparken bir geri arama işlevi iletirsiniz. İstek sonucu geri aramada işlenir.

    • Asenkron bir istek sırasında bir özel durum oluştuğunda, özel durum geri arama işlevinde işlenir.

    • Asenkron bir arayüzün çağrılması doğrudan bir Task döndürür.

      OSSAsyncTask task = oss.asyncGetObejct(...);
      task.cancel(); // Cancel the task.
      task.waitUntilFinished(); // Wait until the task is complete.
      GetObjectResult result = task.getResult(); // Block the thread and wait for the result.