Tous les produits
Search
Centre de documentation

Object Storage Service:Téléchargement par plage (OSS SDK for Java 1.0)

Dernière mise à jour :Aug 18, 2026

Le téléchargement par plage vous permet de télécharger une plage spécifique de données d'un objet.

Notes

  • Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un endpoint interne. Pour plus de détails sur les régions et endpoints pris en charge, consultez Régions et endpoints.

  • Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour plus d'informations sur la configuration des identifiants d'accès, consultez Configuration des identifiants d'accès.

  • Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configuration du client.

  • Pour effectuer un téléchargement par plage, vous devez disposer de l'autorisation oss:GetObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Spécifiez une plage valide pour télécharger des données

L'exemple de code suivant montre comment spécifier une plage valide pour télécharger des données :

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

Le téléchargement en flux continu peut ne pas lire toutes les données en une seule fois. Pour lire 64 Ko de données depuis OSS en mode flux continu, utilisez la méthode suivante pour lire les données plusieurs fois jusqu'à ce que 64 Ko de données ou l'intégralité de l'objet soient lus. Pour plus d'informations, consultez InputStream.read.

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

Spécifiez une plage non valide pour télécharger des données

Pour un objet dont la taille est de 1 000 octets, la plage valide s'étend de l'octet 0 à l'octet 999. Si la plage spécifiée ne se situe pas entre l'octet 0 et l'octet 999, elle n'est pas prise en compte. Dans ce cas, OSS renvoie le code d'état HTTP 200 et les données de l'objet entier. Les exemples suivants présentent des requêtes non valides et les résultats renvoyés :

  • Si vous définissez Range: bytes sur 500-2000, la valeur de fin de plage est non valide. Dans ce cas, OSS renvoie le code d'état HTTP 200 et les données de l'objet entier.

  • Si vous définissez Range: bytes sur 1000-2000, la valeur de début de plage est non valide. Dans ce cas, OSS renvoie le code d'état HTTP 200 et les données de l'objet entier.

Spécifiez les comportements standards pour télécharger des données par plage

Si vous ajoutez x-oss-range-behavior:standard à l'en-tête de la requête, le comportement de téléchargement est modifié lorsque la plage spécifiée n'est pas dans la plage valide. Pour un objet dont la taille est de 1 000 octets :

  • Si vous définissez Range: bytes sur 500-2000, la valeur de fin de plage est non valide. Dans ce cas, OSS renvoie le code d'état HTTP 206 et les données comprises entre l'octet 500 et l'octet 999.

  • Si vous définissez Range: bytes sur 1000-2000, la valeur de début de plage est non valide. Dans ce cas, OSS renvoie le code d'état HTTP 416 et le code d'erreur InvalidRange.

L'exemple de code suivant montre comment spécifier les comportements standards pour télécharger des données par plage :

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

Références

Pour plus d'informations sur l'opération API permettant d'effectuer un téléchargement par plage, consultez GetObject.