Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:Aralık indirme (OSS SDK for Java 1.0)

Son Güncelleme:Oct 01, 2026

Aralık indirme özelliğini kullanarak bir nesnenin verilerinin belirli bir bölümünü indirebilirsiniz.

Notlar

  • Bu konuda Çin (Hangzhou) bölgesinin genel uç noktası kullanılmaktadır. Aynı bölgedeki diğer Alibaba Cloud hizmetlerinden OSS'e erişmek için dahili uç noktayı kullanın. Desteklenen bölgeler ve uç noktalar hakkında daha fazla bilgi için bkz. Bölgeler ve uç noktalar.

  • Bu konuda erişim kimlik bilgileri ortam değişkenlerinden alınmaktadır. Erişim kimlik bilgilerinin nasıl yapılandırılacağı hakkında daha fazla bilgi için bkz. Erişim Kimlik Bilgilerini Yapılandırma.

  • Bu konu, bir OSS uç noktası kullanarak bir OSSClient örneği oluşturmayı göstermektedir. Özel bir alan adı kullanma veya Security Token Service (STS) kimlik bilgileriyle kimlik doğrulama gibi alternatif yapılandırmalar için bkz. İstemci yapılandırması.

  • Aralık indirme işlemi gerçekleştirebilmek için oss:GetObject iznine sahip olmanız gerekir. Daha fazla bilgi için bkz. Özel bir ilke atayın.

Veri indirmek için geçerli bir aralık belirtin

Aşağıdaki örnek kod, veri indirmek için geçerli bir aralığın nasıl belirtileceğini göstermektedir:

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import java.io.InputStream;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        InputStream in = null;
        try {
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
            // For an object whose size is 1,000 bytes, the valid range is from byte 0 to byte 999. 
            // Query the data that is within the range of byte 0 to byte 999, which includes a total of 1,000 bytes. If the specified range is invalid, the entire object is downloaded. For example, if the specified range includes a negative number or the specified value is greater than the object size, all content of the object is downloaded. 
            getObjectRequest.setRange(0, 999);

            // Start range download. 
            OSSObject ossObject = ossClient.getObject(getObjectRequest);

            // Read data. 
            byte[] buf = new byte[1024];
            in = ossObject.getObjectContent();
            for (int n = 0; n != -1; ) {
                n = in.read(buf, 0, buf.length);
            }
            ossObject.close();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            // You must close the obtained stream after the data is read. Otherwise, connection leaks may occur. Consequently, no connections are available and an exception occurs. 
            if (in != null) {
                in.close();
            }
        }
    }
}            

Akış tabanlı indirme sırasında tüm veriler tek seferde okunmayabilir. OSS'ten akış modunda 64 KB'lık veri okumak için, 64 KB'lık veri veya nesnenin tamamı okunana kadar verileri birden çok kez okuyan aşağıdaki yöntemi kullanabilirsiniz. Daha fazla bilgi için InputStream.read sayfasını ziyaret edin.

byte[] buf = new byte[1024];
InputStream in = ossObject.getObjectContent();
for (int n = 0; n != -1; ) {
    n = in.read(buf, 0, buf.length);
}
in.close();

Veri indirmek için geçersiz bir aralık belirtin

Boyutu 1.000 bayt olan bir nesne için geçerli aralık 0. bayttan 999. bayta kadardır. Belirtilen aralık 0-999 bayt aralığında değilse, bu aralık geçerli olmaz. Bu durumda OSS, HTTP durum kodu 200 döndürür ve nesnenin tüm verilerini gönderir. Aşağıdaki örneklerde geçersiz istekler ve döndürülen sonuçlar gösterilmektedir:

  • Range: bytes değerini 500-2000 olarak ayarlarsanız, aralığın sonundaki değer geçersiz olur. Bu durumda OSS, HTTP durum kodu 200 döndürür ve nesnenin tüm verilerini gönderir.

  • Range: bytes değerini 1000-2000 olarak ayarlarsanız, aralığın başındaki değer geçersiz olur. Bu durumda OSS, HTTP durum kodu 200 döndürür ve nesnenin tüm verilerini gönderir.

Verileri aralığa göre indirmek için standart davranışları belirtin

İstek üst bilgisine x-oss-range-behavior:standard eklerseniz, belirtilen aralık geçerli aralık dışında kaldığında indirme davranışı değiştirilir. Boyutu 1.000 bayt olan bir nesne için:

  • Range: bytes değerini 500-2000 olarak ayarlarsanız, aralığın sonundaki değer geçersiz olur. Bu durumda OSS, HTTP durum kodu 206 döndürür ve 500-999 bayt aralığındaki verileri gönderir.

  • Range: bytes değerini 1000-2000 olarak ayarlarsanız, aralığın başındaki değer geçersiz olur. Bu durumda OSS, HTTP durum kodu 416 ve InvalidRange hata kodunu döndürür.

Aşağıdaki örnek kod, verileri aralığa göre indirmek için standart davranışların nasıl belirtileceğini göstermektedir:

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();

        try {
            // If the value at the end of the range is invalid, OSS returns HTTP status code 206 and the data that is within the range of byte 500 to byte 999. 
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
            getObjectRequest.setRange(500, 2000);
            getObjectRequest.addHeader("x-oss-range-behavior", "standard");
            OSSObject ossObject = ossClient.getObject(getObjectRequest);
            ossObject.close();

            System.out.println("standard get " + "500~2000 "+ "statusCode:"  + ossObject.getResponse().getStatusCode());
            System.out.println("standard get " + "500~2000 " + "contentLength:" + ossObject.getResponse().getContentLength());

            // If the value at the start of the range is invalid, exceptions are returned for the following code. OSS returns HTTP status code 416 and the InvalidRange error code. 
            getObjectRequest = new GetObjectRequest(bucketName, objectName);
            getObjectRequest.setRange(1000, 2000);
            getObjectRequest.addHeader("x-oss-range-behavior", "standard");
            OSSObject ossObject2 = ossClient.getObject(getObjectRequest);
            ossObject2.close();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Referans

Aralık indirme gerçekleştiren API işlemi hakkında daha fazla bilgi için bkz. GetObject.