Todos os produtos
Search
Central de documentação

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

Última atualização: Sep 22, 2026

Ao baixar um único objeto de um bucket, especifique condições com base na data e hora da última modificação ou no ETag. Se as condições forem atendidas, o sistema baixa o objeto; caso contrário, retorna um erro. O download condicional reduz a transferência de rede e o consumo de recursos.

Condições de download

O OSS oferece suporte às seguintes condições de download.

Nota
  • Use If-Modified-Since e If-Unmodified-Since em conjunto, assim como If-Match e If-None-Match.

  • Obtenha o ETag chamando o método ossClient.getObjectMeta.

Parâmetro

Descrição

If-Modified-Since

Se a data e hora especificada for anterior à data e hora da última modificação do objeto, o sistema baixa o objeto. Caso contrário, retorna o código 304 Not Modified.

If-Unmodified-Since

Se a data e hora especificada for igual ou posterior à data e hora da última modificação do objeto, o sistema baixa o objeto. Caso contrário, retorna o código 412 Precondition Failed.

If-Match

Se o ETag especificado corresponder ao ETag do objeto, o sistema baixa o objeto. Caso contrário, retorna o código 412 Precondition Failed.

If-None-Match

Se o ETag especificado não corresponder ao ETag do objeto, o sistema baixa o objeto. Caso contrário, retorna o código 304 Not Modified.

Observações de uso

  • 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 mais informações sobre as regiões e os endpoints suportados pelo OSS, consulte Regions and endpoints.

  • Este tópico usa credenciais de acesso obtidas de variáveis de ambiente. Para mais informações, 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.

  • O download condicional requer a permissão oss:GetObject. Para mais informações, consulte Grant a custom policy.

Exemplos

O código a seguir baixa um objeto condicionalmente usando o método ossClient.getObject. Também é possível usar o método ossClient.downloadFile de forma semelhante.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
import java.util.Date;

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. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt. 
        String objectName = "testfolder/exampleobject.txt";
        String pathName = "D:\\localpath\\examplefile.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 associated 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();

        try {
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            // For example, an object was last modified at 13:27:04, September 26, 2023. If the specified time is earlier than the last modified time, such as Tue Sep 25 13:27:04 CST 2023, the object meets the If-Modified-Since condition and the object is downloaded. 
            request.setModifiedSinceConstraint(new Date("Tue Sep 25 13:27:04 CST 2023"));

            // Download the object to your local device. 
            ossClient.getObject(request, new File(pathName));
        } 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ências

Para obter mais informações sobre a operação de API usada para fazer download condicional, consulte GetObject.