Todos os produtos
Search
Central de documentação

Object Storage Service:Download por intervalo (OSS SDK for Java 1.0)

Última atualização: Sep 22, 2026

O download por intervalo permite baixar um intervalo específico de dados de um objeto.

Observações

  • Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e os endpoints compatíveis, consulte Regions and endpoints.

  • Neste tópico, o exemplo obtém as credenciais de acesso de variáveis de ambiente. Para obter mais informações sobre como configurar as credenciais de acesso, consulte 配置访问凭证.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Client configuration.

  • Para baixar dados por intervalo, você precisa da permissão oss:GetObject. Para obter mais informações, consulte Grant a custom policy.

Especifique um intervalo válido para baixar dados

O código de exemplo a seguir mostra como especificar um intervalo válido para baixar dados:

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

O download por streaming pode não ler todos os dados de uma só vez. Para ler 64 KB de dados do OSS no modo de streaming, use o método a seguir. Leia os dados várias vezes até completar 64 KB ou ler o objeto inteiro. Para obter mais informações, acesse 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();

Especifique um intervalo inválido para baixar dados

Para um objeto de 1.000 bytes, o intervalo válido vai do byte 0 ao byte 999. Se o intervalo especificado não estiver entre o byte 0 e o byte 999, ele não terá efeito. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto. Os exemplos a seguir mostram solicitações inválidas e os resultados retornados:

  • Ao definir Range: bytes como 500-2000, o valor final do intervalo é inválido. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto.

  • Ao definir Range: bytes como 1000-2000, o valor inicial do intervalo é inválido. Nessa situação, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto.

Especifique comportamentos padrão para baixar dados por intervalo

Ao adicionar x-oss-range-behavior:standard ao cabeçalho da solicitação, o comportamento de download muda quando o intervalo especificado não estiver dentro do intervalo válido. Para um objeto de 1.000 bytes:

  • Ao definir Range: bytes como 500-2000, o valor final do intervalo é inválido. Quando isso ocorre, o OSS retorna o código de status HTTP 206 e os dados dentro do intervalo do byte 500 ao byte 999.

  • Ao definir Range: bytes como 1000-2000, o valor inicial do intervalo é inválido. Nesse cenário, o OSS retorna o código de status HTTP 416 e o código de erro InvalidRange.

O código de exemplo a seguir mostra como especificar comportamentos padrão para baixar dados por intervalo:

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

Referência

Para obter mais informações sobre a operação da API para download por intervalo, consulte GetObject.