Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:OSS SDK for Java 2.0 (preview)

Son Güncelleme:Oct 02, 2026

Alibaba Cloud Object Storage Service (OSS) hizmetini Java uygulamalarınıza entegre ederek dosyaları bulutta yükleyin, indirin ve yönetin.

Github | OSS SDK for Java API | mvnrepository | deepwiki

Hızlı entegrasyon

SDK'yı kullanmaya başlamak için aşağıdaki adımları tamamlayın.

image

Ön koşullar

Java 8 veya üzeri bir sürüm gereklidir.

Java sürümünüzü kontrol etmek için java -version komutunu çalıştırın. Java yüklü değilse veya sürüm Java 8'den eskiyse Java'yı indirin ve yükleyin .

SDK'yı yükleyin

SDK bağımlılığını Maven üzerinden ekleyin veya kaynak koddan derleyin.

Maven

Aşağıdaki bağımlılığı pom.xml dosyasına ekleyin. <version> değerini Maven Repository üzerindeki en son sürümle değiştirin.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-oss-v2</artifactId>
    <version><!-- Specify the latest version number--></version>
</dependency>

Kaynak kodu

Depoyu Github adresinden klonlayın ve Maven ile derleyin.

mvn clean install -DskipTests -Dgpg.skip=true

Erişim kimlik bilgilerini yapılandırın

Bir RAM kullanıcısının AccessKey çiftini ortam değişkenleri olarak ayarlayın.

RAM konsol üzerinde Permanent AccessKey Pair erişimine sahip bir RAM kullanıcısı oluşturun. AccessKey çiftini kaydedin ve kullanıcıya AliyunOSSFullAccess iznini verin.

Linux

  1. Komut satırı arayüzünde aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.bashrc dosyasına ekleyin.

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    1. Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.

      source ~/.bashrc
    2. Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

macOS

  1. Varsayılan kabuk türünü kontrol etmek için terminalde aşağıdaki komutu çalıştırın.

    echo $SHELL
    1. Varsayılan kabuk türünüze göre aşağıdaki adımları izleyin.

      Zsh

      1. Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.zshrc dosyasına ekleyin.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.

        source ~/.zshrc
      3. Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Aşağıdaki komutları çalıştırarak ortam değişkeni ayarlarını ~/.bash_profile dosyasına ekleyin.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
      2. Değişiklikleri uygulamak için aşağıdaki komutu çalıştırın.

        source ~/.bash_profile
      3. Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

  1. Komut İstemi'nde aşağıdaki komutları çalıştırın.

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    1. Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. PowerShell'de aşağıdaki komutları çalıştırın.

    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    1. Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

İstemciyi başlatın

Bir bölge belirterek OSSClient'i başlatın.

  • OSSClient, AutoCloseable arayüzünü uygular. try-with-resources bloğu kullanıldığında close() yöntemini çağırmanıza gerek kalmadan kaynaklar otomatik olarak serbest bırakılır.

  • OSSClient örneği oluşturmak ve yok etmek maliyetlidir. Tek bir örneği yeniden kullanmak için singleton desenini uygulayın ve uygulama kapanmadan önce close() yöntemini açıkça çağırın.

    Singleton deseni

    public class OssClientSingleton {
        private OssClientSingleton() {}
    
        private static class Holder {
            private static final OSSClient INSTANCE = OSSClient.newBuilder()
                .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                .region("cn-hangzhou")
                .build();
        }
    
        public static OSSClient getInstance() {
            return Holder.INSTANCE;
        }
    
        // Close the OSSClient instance. This must be explicitly called.
        public static void shutdown() {
            try {
                getInstance().close();
            } catch (Exception e) {
                // Handle the close exception.
            }
        }
    }
    

Senkron OSSClient

Her işlemin tamamlanmasını beklemeniz gerektiğinde senkron istemciyi kullanın.

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.exceptions.ServiceException;
import com.aliyun.sdk.service.oss2.models.*;
import com.aliyun.sdk.service.oss2.paginator.ListBucketsIterable;

public class Example {
    public static void main(String[] args) {
        String region = "cn-hangzhou";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        OSSClientBuilder clientBuilder = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region(region);

        try (OSSClient client = clientBuilder.build()) {

            ListBucketsIterable paginator = client.listBucketsPaginator(
                    ListBucketsRequest.newBuilder()
                            .build());

            for (ListBucketsResult result : paginator) {
                for (BucketSummary info : result.buckets()) {
                    System.out.printf("bucket: name:%s, region:%s, storageClass:%s\n", info.name(), info.region(), info.storageClass());
                }
            }

        } catch (Exception e) {
//            ServiceException se = ServiceException.asCause(e);
//            if (se != null) {
//                System.out.printf("ServiceException: requestId:%s, errorCode:%s\n", se.requestId(), se.errorCode());
//            }
            System.out.printf("error:\n%s", e);
        }
    }
}

Eşzamansız OSSClient

Birden fazla OSS işlemini engellemeden eş zamanlı olarak çalıştırmak için eşzamansız istemciyi kullanın.

import com.aliyun.sdk.service.oss2.OSSAsyncClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.exceptions.ServiceException;
import com.aliyun.sdk.service.oss2.models.*;

import java.util.concurrent.CompletableFuture;

public class ExampleAsync {
    public static void main(String[] args) {
        String region = "cn-hangzhou";
        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();

        try (OSSAsyncClient client = OSSAsyncClient.newBuilder()
                .region(region)
                .credentialsProvider(provider)
                .build()) {

            CompletableFuture<ListBucketsResult> future = client.listBucketsAsync(
                    ListBucketsRequest.newBuilder().build()
            );

            future.thenAccept(result -> {
                        for (BucketSummary info : result.buckets()) {
                            System.out.printf("bucket: name:%s, region:%s, storageClass:%s\n",
                                    info.name(), info.region(), info.storageClass());
                        }
                    })
                    .exceptionally(e -> {
//                ServiceException se = ServiceException.asCause(e);
//                if (se != null) {
//                    System.out.printf("Async ServiceException: requestId:%s, errorCode:%s\n",
//                            se.requestId(), se.errorCode());
//                }
                        System.out.printf("async error:\n%s\n", e);
                        return null;
                    });

            future.join();

        } catch (Exception e) {
            System.out.printf("main error:\n%s\n", e);
        }
    }
}

Hesabınızdaki tüm paketleri listeleyen örnek çıktı:

bucket: name: examplebucket01, region: cn-hangzhou, storageClass: Standard
bucket: name: examplebucket02, region: cn-hangzhou, storageClass: Standard

İstemci yapılandırmaları

Desteklenen istemci yapılandırmaları


Parametre adı


Açıklama


region


(Zorunlu) İsteklerin gönderildiği bölge.


credentialsProvider


Erişim kimlik bilgisini ayarlayın (Zorunlu)


endpoint


Erişim uç noktası.


httpClient


HTTP istemcisi.


retryMaxAttempts


Bir HTTP isteği için maksimum yeniden deneme sayısı. Varsayılan değer 3'tür.


retryer


Bir HTTP isteği için yeniden deneme uygulaması.


connectTimeout


Bağlantı kurma zaman aşımı. Varsayılan değer 5 saniyedir.


readWriteTimeout


Veri okuma ve yazma zaman aşımı. Varsayılan değer 20 saniyedir.


insecureSkipVerify


SSL sertifikası doğrulamasını atlar. Varsayılan olarak SSL sertifikaları doğrulanır.


enabledRedirect


HTTP yönlendirmesini etkinleştirir. Varsayılan olarak bu özellik devre dışıdır.


signatureVersion


İmza sürümü. Varsayılan değer v4'tür.


disableSsl


Varsayılan olarak istekler HTTPS üzerinden gönderilir.


usePathStyle


useCName


Erişim için özel bir alan adı kullanır. Varsayılan olarak false değerindedir.


useDualStackEndpoint


Erişim için çift yığın uç noktası kullanır. Varsayılan olarak false değerindedir.


useAccelerateEndpoint


Erişim için hızlandırma aktarım uç noktası kullanır. Varsayılan olarak false değerindedir.


useInternalEndpoint


Erişim için dahili aynı bölge uç noktası kullanır. Varsayılan olarak false değerindedir.


additionalHeaders


İmzalanacak ek istek üstbilgileri. Bu, V4 imzaları için geçerlidir.


userAgent


Ek User-Agent bilgisi.

Özel bir alan adı kullanın

Varsayılan OSS alan adının kullanılması dosyalara erişilememesine veya önizlemenin başarısız olmasına neden olabilir. Tarayıcı önizlemesini ve CDN hızlandırmayı etkinleştirmek için özel bir alan adı bağlayın.

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Specify your custom domain name. For example, www.example-***.com.
        String endpoint = "https://www.example-***.com";

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .endpoint(endpoint)
                // Note: Set useCName to true to enable the CNAME option. Otherwise, you cannot use a custom domain name.
                .useCName(true)
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Zaman aşımı kontrolü

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import java.time.Duration;

public class Example {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                // Set the timeout for establishing a connection. The default value is 5 seconds.
                .connectTimeout(Duration.ofSeconds(30))
                // Set the timeout for reading and writing data. The default value is 20 seconds.
                .readWriteTimeout(Duration.ofSeconds(30))
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Yeniden deneme ilkesi

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import com.aliyun.sdk.service.oss2.retry.*;
import java.time.Duration;

public class Example {
    public static void main(String[] args) {
        /*
         * SDK retry policy configuration description:
         *
         * Default retry policy:
         * When no retry policy is configured, the SDK uses StandardRetryer as the default client implementation.
         * Its default configuration is as follows:
         * - maxAttempts: Sets the maximum number of attempts. The default is 3.
         * - maxBackoff: Sets the maximum backoff time in seconds. The default is 20 seconds.
         * - baseDelay: Sets the base delay time in seconds. The default is 0.2 seconds.
         * - backoffDelayer: Sets the backoff algorithm. The default is the FullJitter backoff algorithm.
         *   Formula: [0.0, 1.0) * min(2^attempts * baseDelay, maxBackoff)
         * - errorRetryables: Retryable error types, including HTTP status codes, service error codes, and client errors.
         *
         * When a retryable error occurs, the provided configuration is used to delay and then retry the request.
         * The overall latency of the request increases with the number of retries. If the default configuration
         * does not meet your scenario requirements, you can configure retry parameters or modify the retry implementation.
         */

        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Retry policy configuration example:

        // 1. Customize the maximum number of retries (default is 3, here set to 5).
        Retryer customRetryer = StandardRetryer.newBuilder()
                .maxAttempts(5)
                .build();

        // 2. Customize the backoff delay time.
        // Adjust the baseDelay to 0.5 seconds (default 0.2 seconds) and maxBackoff to 25 seconds (default 20 seconds).
        // Retryer customRetryer = StandardRetryer.newBuilder()
        //         .backoffDelayer(new FullJitterBackoff(Duration.ofMillis(500), Duration.ofSeconds(25)))
        //         .build();

        // 3. Customize the backoff algorithm.
        // Use a fixed-delay backoff algorithm instead of the default FullJitter algorithm, with a 2-second delay each time.
        // Retryer customRetryer = StandardRetryer.newBuilder()
        //         .backoffDelayer(new FixedDelayBackoff(Duration.ofSeconds(2)))
        //         .build();

        // 4. Disable the retry policy.
        // To disable all retry attempts, use the NopRetryer implementation.
        // Retryer customRetryer = new NopRetryer();

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .retryer(customRetryer)
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

HTTP/HTTPS protokolü

HTTPS protokolünü devre dışı bırakmak için disableSsl(true) kullanın.

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                // Set to not use HTTPS requests.
                .disableSsl(true)
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Dahili uç nokta kullanın

Aynı bölge içinde OSS'e erişmek için dahili uç nokta kullanarak trafik maliyetlerini düşürün ve hızı artırın.

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Method 1: Specify the region and set useInternalEndpoint to true.
        // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // // Method 2: Directly specify the region and endpoint.
        // // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        // String region = "cn-hangzhou";
        // // Specify the internal endpoint for the bucket's region. For China (Hangzhou), the endpoint is 'oss-cn-hangzhou-internal.aliyuncs.com'.
        // String endpoint = "oss-cn-hangzhou-internal.aliyuncs.com";

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .useInternalEndpoint(true)
                // .endpoint(endpoint) // If using Method 2, uncomment this line and comment out the previous one.
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Hızlandırma aktarım uç noktası kullanın

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Method 1: Specify the region and set useAccelerateEndpoint to true.
        // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // // Method 2: Directly specify the region and transfer acceleration endpoint.
        // // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        // String region = "cn-hangzhou";
        // // Specify the transfer acceleration endpoint for the bucket's region, for example, 'https://oss-accelerate.aliyuncs.com'.
        // String endpoint = "https://oss-accelerate.aliyuncs.com";

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .useAccelerateEndpoint(true)
                // .endpoint(endpoint) // If using Method 2, uncomment this line and comment out the previous one.
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Özel alan kullanın

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Specify your private domain. For example: https://service.corp.example.com
        String endpoint = "https://service.corp.example.com";

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .endpoint(endpoint)
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Devlet Bulutu alan adı kullanın

Bir Alibaba Gov Cloud alan adı kullanarak bir OSSClient yapılandırın.

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;

public class Example {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region and endpoint.
        // Specify the region where the bucket is located. For China (Beijing) Gov Cloud 1, set the region to cn-north-2-gov-1.
        String region = "cn-north-2-gov-1";
        // Specify the internal endpoint for the bucket's region. For China (Beijing) Gov Cloud 1, the endpoint is 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
        // To specify the HTTP protocol, set the domain to 'http://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
        String endpoint = "https://oss-cn-north-2-gov-1-internal.aliyuncs.com";

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .endpoint(endpoint)
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Özel HTTPClient kullanın

Standart yapılandırma parametreleri yetersiz kaldığında özel bir HTTP istemcisi kullanın.

import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import com.aliyun.sdk.service.oss2.transport.HttpClient;
import com.aliyun.sdk.service.oss2.transport.HttpClientOptions;
import com.aliyun.sdk.service.oss2.transport.apache5client.Apache5HttpClientBuilder;
import java.time.Duration;

public class Example {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

        // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Set the parameters for the HTTP client.
        HttpClientOptions httpClientOptions = HttpClientOptions.custom()
                // Connection timeout. The default value is 5 seconds.
                .connectTimeout(Duration.ofSeconds(30))
                // Timeout for reading and writing data. The default value is 20 seconds.
                .readWriteTimeout(Duration.ofSeconds(30))
                // Maximum number of connections. The default value is 1024.
                .maxConnections(2048)
                // Specifies whether to skip certificate verification. By default, this is false.
                .insecureSkipVerify(false)
                // Specifies whether to enable HTTP redirection. By default, this is disabled.
                .redirectsEnabled(false)
                // Set the proxy server.
                // .proxyHost("http://user:passswd@proxy.example-***.com")
                .build();

        // Create an HTTP client and pass in the HTTP client parameters.
        HttpClient httpClient = Apache5HttpClientBuilder.create()
                .options(httpClientOptions)
                .build();

        // Create an OSS client with the configured information.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region(region)
                .httpClient(httpClient)
                .build()) {

            // Use the created client for subsequent operations...

        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

Erişim kimlik bilgisi yapılandırmaları

SDK, birden fazla kimlik bilgisi türünü destekler. Kimlik doğrulama ihtiyaçlarınıza en uygun yöntemi seçin.

Erişim kimlik bilgilerinin nasıl seçileceği


Kimlik bilgisi sağlayıcısı başlatma yöntemi


Senaryo


Java SDK 2.0 desteği


Alt düzey kimlik bilgileri


Kimlik bilgisi geçerliliği


Kimlik bilgisi döndürme veya yenileme yöntemi


RAM kullanıcısının AccessKey çiftini kullanın


Sık kimlik bilgisi döndürmesi gerektirmeyen, güvenli bir ortamda uzun süreli erişim isteyen uygulamalar.


Yerleşik destek


AccessKey


Uzun vadeli


Manuel döndürme


STS belirtecini kullanın


Erişimin geçerlilik süresini ve izinlerini kontrol ettiğiniz güvensiz ortamlardaki uygulamalar.


Yerleşik destek


Security Token Service belirteci


Geçici


Manuel yenileme


RAM rolü ARN kimlik bilgilerini kullanın


Bir RAM rolü üstlenerek geçici kimlik bilgileri almayı gerektiren, hesaplar arası OSS erişimi.


Genişletilmiş destek


Security Token Service belirteci


Geçici


Otomatik yenileme


ECS RAM rolü kimlik bilgilerini kullanın


ECS örnekleri, ECI örnekleri veya Container Service for Kubernetes üzerindeki uygulamalar.


Genişletilmiş destek


Security Token Service belirteci


Geçici


Otomatik yenileme


OIDC rolü ARN kimlik bilgilerini kullanın


Pod düzeyinde izin yalıtımı için Container Service for Kubernetes içindeki RRSA.


Genişletilmiş destek


Security Token Service belirteci


Geçici


Otomatik yenileme


Özel erişim kimlik bilgilerini kullanın


Yukarıdaki yöntemlerin yetersiz kaldığı durumlarda özel kimlik bilgisi alma.


Yerleşik destek


Özel


Özel


Özel


Anonim erişim


Kimlik bilgisi olmadan genel okuma OSS kaynaklarına erişim.


Yerleşik destek


Yok


Yok


Yok

Genişletilmiş destek olarak işaretlenen kimlik bilgisi özellikleri, özel erişim kimlik bilgileri yöntemi ve Alibaba Cloud kimlik bilgileri yönetim kitaplığı kullanılarak uygulanmalıdır. SDK, temel kimlik bilgisi yapılandırma yöntemleri için yerleşik destek sunar. Genişletilmiş özellikleri, credentials-java kitaplığını entegre ederek uygulayabilirsiniz.

RAM kullanıcısının AccessKey çiftini kullanın

Kimlik bilgisi sağlayıcısını bir Alibaba Cloud hesabının veya RAM kullanıcısının AccessKey çifti (AccessKey ID ve AccessKey secret) ile başlatın. Uzun süreli OSS erişimine ihtiyaç duyan ve güvenli bir ortamda çalışan uygulamalar için uygundur. Bu yaklaşım manuel anahtar bakımı gerektirdiğinden güvenlik riskini artırır.

Önemli
  • Bir Alibaba Cloud hesabı, kaynakları üzerinde tam izne sahiptir. Hesabın AccessKey çiftinin sızdırılması önemli bir güvenlik riski oluşturur. Bunun yerine, minimum gerekli izinlere sahip bir RAM kullanıcısı kullanın.

  • Bir RAM kullanıcısı için AccessKey çifti oluşturmak üzere bkz. AccessKey çifti oluşturma. AccessKey ID ve secret yalnızca oluşturma sırasında görüntülenir. Bunları hemen kaydedin. Kaybolursa yeni bir çift oluşturun.

Ortam değişkenlerini yapılandırın

Linux/macOS

  1. RAM kullanıcısının AccessKey çiftini kullanarak ortam değişkenlerini ayarlayın.

    export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'
    export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'
  2. Ortam değişkenlerinin yapılandırıldığını doğrulamak için aşağıdaki komutları çalıştırın.

    echo $OSS_ACCESS_KEY_ID
    echo $OSS_ACCESS_KEY_SECRET

Windows

CMD

setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"

PowerShell

[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Kod örneği

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Load credential information from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Statik kimlik bilgisi yapılandırması

AccessKey çiftini açıkça ayarlayarak erişim kimlik bilgilerini sabit kodlayın.

Uyarı

Erişim kimlik bilgilerini üretim uygulamalarınıza gömmeyin. Bu yöntem yalnızca test amaçlıdır.

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Create a static credential provider and explicitly set the AccessKey pair.
        // Replace with your RAM user's AccessKey ID and AccessKey secret.
        CredentialsProvider credentialsProvider = new StaticCredentialsProvider(
                "YOUR_ACCESS_KEY_ID",
                "YOUR_ACCESS_KEY_SECRET"
        );
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

STS belirtecini kullanın

Zaman sınırlı OSS erişimi için Security Token Service (STS) üzerinden alınan geçici kimlik bilgilerini — bir AccessKey ID, bir AccessKey secret ve bir güvenlik belirteci — kullanın. Belirtecin süresi dolmadan önce manuel olarak yenilemeniz gerekir.

Ortam değişkenlerini yapılandırın

Önemli
  • Bu yöntem, bir RAM kullanıcısının AccessKey çiftini değil, STS'den aldığınız geçici kimlik kimlik bilgilerini (AccessKey ID, AccessKey secret ve Security Token Service (STS) belirteci) kullanır.

  • STS'den aldığınız AccessKey ID "STS" ile başlar, örneğin "STS.L4aBSCSJVMuKg5U1****".

Linux/macOS

export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

Windows

set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

Kod örneği

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Load the authentication information required to access OSS from environment variables for identity verification.
        CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Statik kimlik bilgisi yapılandırması

AccessKey çiftini ve güvenlik belirtecini açıkça ayarlayarak geçici kimlik bilgilerini sabit kodlayın.

Uyarı

Erişim kimlik bilgilerini üretim uygulamalarınıza gömmeyin. Bu yöntem yalnızca test amaçlıdır.

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Specify the obtained temporary AccessKey ID and AccessKey secret.
        // Note that the AccessKey ID obtained from STS starts with "STS".
        String stsAccessKeyId = "STS.****************";
        String stsAccessKeySecret = "yourAccessKeySecret";
        String stsSecurityToken = "yourSecurityToken";
        
        // Create a static credential provider and explicitly set the temporary AccessKey pair and STS security token.
        CredentialsProvider credentialsProvider = new StaticCredentialsProvider(
                stsAccessKeyId,
                stsAccessKeySecret,
                stsSecurityToken
        );
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

RAM rolü ARN kimlik bilgilerini kullanın

Hesaplar arası erişim için, bir kimlik bilgisi sağlayıcısını başlatmak amacıyla bir RAM rolünün ARN'sini kullanın. SDK, STS belirteçlerini otomatik olarak almak ve yenilemek için AssumeRole'u çağırır. İzinleri daha da kısıtlamak için policy parametresini ayarlayabilirsiniz.

Önemli
  • Bir Alibaba Cloud hesabı, kaynakları üzerinde tam izne sahiptir. Hesabın AccessKey çiftinin sızdırılması önemli bir güvenlik riski oluşturur. Bunun yerine, minimum gerekli izinlere sahip bir RAM kullanıcısı kullanın.

  • Bir RAM kullanıcısı için AccessKey çifti oluşturmak üzere bkz. AccessKey çifti oluşturma. AccessKey ID ve secret yalnızca oluşturma sırasında görüntülenir. Bunları hemen kaydedin. Kaybolursa yeni bir çift oluşturun.

  • Bir RAM rolü ARN'si almak için bkz. RAM rolü oluşturma.

Bağımlılık ekleyin

Alibaba Cloud kimlik bilgileri yönetimi bağımlılığını pom.xml dosyanıza ekleyin.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>credentials-java</artifactId>
    <version>0.3.4</version>
</dependency>

Erişim kimlik bilgisi olarak AccessKey çiftini ve RAM rolü ARN'sini yapılandırın

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class OSSExample {
    public static void main(String[] args) {
        // Configure RAM role ARN credentials.
        Config credentialConfig = new Config()
                .setType("ram_role_arn")
                // Obtain the RAM user's AccessKey pair (AccessKey ID and AccessKey secret) from environment variables.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                // The ARN of the RAM role to assume. Example value: acs:ram::123456789012****:role/adminrole
                // You can set the RoleArn via the ALIBABA_CLOUD_ROLE_ARN environment variable.
                .setRoleArn("acs:ram::123456789012****:role/adminrole")
                // The role session name. You can set the RoleSessionName via the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                .setRoleSessionName("your-session-name")
                // Set a more restrictive permission policy. This is optional. Example value: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                .setPolicy("{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}")
                // Set the role session validity period in seconds. The default is 3600 seconds (1 hour). This is optional.
                .setRoleSessionExpiration(3600);

        Client credentialClient = new Client(credentialConfig);

        // Create a credential provider for dynamic credential loading.
        CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
            try {
                com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
                return new Credentials(
                    cred.getAccessKeyId(),
                    cred.getAccessKeySecret(),
                    cred.getSecurityToken()
                );
            } catch (Exception e) {
                throw new RuntimeException("Failed to obtain credentials", e);
            }
        });

        // Create an OSS client instance.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located, for example, China (Hangzhou).
                .build()) {
            
            // Use the client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

ECS RAM rolü kimlik bilgilerini kullanın

ECS örnekleri, ECI örnekleri veya Container Service for Kubernetes worker düğümleri üzerindeki uygulamalar için bir ECS RAM rolü kullanın. SDK, geçici STS belirteçlerini otomatik olarak alır ve yeniler; manuel anahtar yönetimi gerekmez. Rolü kurmak için bkz. RAM rolü oluşturma.

Bağımlılık ekleyin

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>credentials-java</artifactId>
    <version>0.3.4</version>
</dependency>

Erişim kimlik bilgisi olarak bir ECS RAM rolünü yapılandırın

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class OSSExample {
    public static void main(String[] args) {
        // Configure ECS RAM role credentials.
        Config credentialConfig = new Config()
                .setType("ecs_ram_role")      // Access credential type. Fixed as ecs_ram_role.
                .setRoleName("EcsRoleExample"); // The name of the RAM role granted to the ECS instance. Optional parameter. If not set, it will be automatically retrieved. We strongly recommend setting it to reduce requests.

        Client credentialClient = new Client(credentialConfig);

        // Create a credential provider for dynamic credential loading.
        CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
            try {
                com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
                return new Credentials(
                    cred.getAccessKeyId(),
                    cred.getAccessKeySecret(),
                    cred.getSecurityToken()
                );
            } catch (Exception e) {
                throw new RuntimeException("Failed to obtain credentials", e);
            }
        });

        // Create an OSS client instance.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located, for example, China (Hangzhou).
                .build()) {
            
            // Use the client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

OIDC rolü ARN kimlik bilgilerini kullanın

Container Service for Kubernetes içinde, pod düzeyinde izin denetimi için Hizmet Hesapları için RAM Rolleri (RRSA) kullanın. SDK, bir RAM rolünü üstlenmek ve otomatik olarak geçici STS belirteçleri almak için pod'a monte edilen bir OIDC belirteci kullanır. ServiceAccount'a RAM izinleri vermek için RRSA'yı kullanın.

Bağımlılık ekleyin

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>credentials-java</artifactId>
    <version>0.3.4</version>
</dependency>

Erişim kimlik bilgisi olarak bir OIDC rolü ARN'sini yapılandırın

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;

public class OSSExample {
    public static void main(String[] args) {
        // Configure OIDC role ARN credentials.
        Config credentialConfig = new Config()
                // Specify the credential type. Fixed as oidc_role_arn.
                .setType("oidc_role_arn")
                // The RAM role ARN. You can set the RoleArn via the ALIBABA_CLOUD_ROLE_ARN environment variable.
                .setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"))
                // The OIDC provider ARN. You can set the OidcProviderArn via the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
                .setOidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN"))
                // The OIDC token file path. You can set the OidcTokenFilePath via the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
                .setOidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE"))
                // The role session name. You can set the RoleSessionName via the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                .setRoleSessionName("your-session-name")
                // Set a more restrictive permission policy. This is optional. Example value: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                .setPolicy("{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}")
                // Set the role session validity period in seconds. The default is 3600 seconds (1 hour). This is optional.
                .setRoleSessionExpiration(3600);

        Client credentialClient = new Client(credentialConfig);

        // Create a credential provider for dynamic credential loading.
        CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
            try {
                com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
                return new Credentials(
                    cred.getAccessKeyId(),
                    cred.getAccessKeySecret(),
                    cred.getSecurityToken()
                );
            } catch (Exception e) {
                throw new RuntimeException("Failed to obtain credentials", e);
            }
        });

        // Create an OSS client instance.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located, for example, China (Hangzhou).
                .build()) {
            
            // Use the client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Özel erişim kimlik bilgilerini kullanın

Yerleşik kimlik bilgisi yöntemleri yetersiz kalırsa özel bir kimlik bilgisi sağlayıcısı uygulayın.

Supplier arabirimi aracılığıyla uygulama

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;

public class OSSExample {
    public static void main(String[] args) {
        // Create a custom credential provider.
        CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
            // TODO: Implement your custom credential retrieval logic.
            
            // Return long-term credentials.
            return new Credentials("access_key_id", "access_key_secret");
            
            // Return an STS token (if needed).
            // return new Credentials("sts_access_key_id", "sts_access_key_secret", "security_token");
        });
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

CredentialsProvider arabirimini uygulayın

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;

public class CustomCredentialsProvider implements CredentialsProvider {
    
    @Override
    public Credentials getCredentials() {
        // TODO: Implement your custom credential retrieval logic.
        
        // Return long-term credentials.
        return new Credentials("access_key_id", "access_key_secret");
        
        // Return an STS token (if needed).
        // For temporary credentials, you need to refresh them based on their expiration time.
        // return new Credentials("sts_access_key_id", "sts_access_key_secret", "security_token");
    }
}

public class OSSExample {
    public static void main(String[] args) {
        // Create a custom credential provider.
        CredentialsProvider credentialsProvider = new CustomCredentialsProvider();
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations...
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Anonim erişim

Kimlik bilgisi sağlamadan genel okuma OSS kaynaklarına erişin.

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.AnonymousCredentialsProvider;

public class OSSExample {
    public static void main(String[] args) {
        // Create an anonymous credential provider.
        CredentialsProvider credentialsProvider = new AnonymousCredentialsProvider();
        
        // Create an OSS client.
        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(credentialsProvider)
                .region("cn-hangzhou") // Specify the region where the bucket is located.
                .build()) {
            
            // Use the created client for subsequent operations...
            // Note: Anonymous access can only be used for resources with public-read permissions.
            
        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}

Örnek kodlar

Özellik sınıflandırması

Örnek açıklaması

Eşzamanlı sürüm

Eşzamansız sürüm

Paket

Paket oluşturun

PutBucket.java

PutBucketAsync.java

Paketleri listeleyin

ListBuckets.java

ListBucketsAsync.java

Paket bilgilerini alın

GetBucketInfo.java

GetBucketInfoAsync.java

Paket bölgesini alın

GetBucketLocation.java

GetBucketLocationAsync.java

Paket depolama istatistiklerini alın

GetBucketStat.java

GetBucketStatAsync.java

Paketi silin

DeleteBucket.java

DeleteBucketAsync.java

Dosya yükleme

Basit yükleme

PutObject.java

PutObjectAsync.java

Ekleme yöntemiyle yükleme

AppendObject.java

AppendObjectAsync.java

Çok parçalı yükleme

MultipartUpload.java

MultipartUploadAsync.java

Çok parçalı yükleme görevlerini listeleyin

ListMultipartUploads.java

ListMultipartUploadsAsync.java

Yüklenen parçaları listeleyin

ListParts.java

ListPartsAsync.java

Çok parçalı yüklemeyi iptal edin

AbortMultipartUpload.java

AbortMultipartUploadAsync.java

Dosya indirme

Basit indirme

GetObject.java

GetObjectAsync.java

Dosya yönetimi

Dosyayı kopyalayın

CopyObject.java

CopyObjectAsync.java

Dosyanın var olup olmadığını kontrol edin

HeadObject.java

HeadObjectAsync.java

Dosyaları listeleyin

ListObjects.java

ListObjectsAsync.java

Dosyaları V2 ile listeleyin

ListObjectsV2.java

ListObjectsV2Async.java

Dosyayı silin

DeleteObject.java

DeleteObjectAsync.java

Birden fazla dosyayı silin

DeleteMultipleObjects.java

DeleteMultipleObjectsAsync.java

Dosya meta verilerini alın

GetObjectMeta.java

GetObjectMetaAsync.java

Arşivlenmiş nesne

Dosyayı geri yükleyin

RestoreObject.java

RestoreObjectAsync.java

Geri yüklenmiş dosyayı temizleyin

CleanRestoredObject.java

CleanRestoredObjectAsync.java

Sembolik bağlantı

Sembolik bağlantı oluşturun

PutSymlink.java

PutSymlinkAsync.java

Sembolik bağlantıyı alın

GetSymlink.java

GetSymlinkAsync.java

Nesne etiketleme

Nesne etiketlerini ayarlayın

PutObjectTagging.java

PutObjectTaggingAsync.java

Nesne etiketlerini alın

GetObjectTagging.java

GetObjectTaggingAsync.java

Nesne etiketlerini silin

DeleteObjectTagging.java

DeleteObjectTaggingAsync.java

Erişim kontrolü

Paket ACL'sini ayarlayın

PutBucketAcl.java

PutBucketAclAsync.java

Paket ACL'sini alın

GetBucketAcl.java

GetBucketAclAsync.java

Nesne ACL'sini ayarlayın

PutObjectAcl.java

PutObjectAclAsync.java

Nesne ACL'sini alın

GetObjectAcl.java

GetObjectAclAsync.java

Sürüm oluşturma

Sürüm oluşturmayı ayarlayın

PutBucketVersioning.java

PutBucketVersioningAsync.java

Sürüm oluşturma durumunu alın

GetBucketVersioning.java

GetBucketVersioningAsync.java

Nesne sürümlerini listeleyin

ListObjectVersions.java

ListObjectVersionsAsync.java

Çapraz alan erişimi

CORS kurallarını ayarlayın

PutBucketCors.java

PutBucketCorsAsync.java

CORS kurallarını alın

GetBucketCors.java

GetBucketCorsAsync.java

CORS kurallarını silin

DeleteBucketCors.java

DeleteBucketCorsAsync.java

Hazırlık isteği

OptionObject.java

OptionObjectAsync.java

Sistem özellikleri

Uç nokta bilgilerini sorgulayın

DescribeRegions.java

DescribeRegionsAsync.java