Ao baixar um único objeto de um bucket, defina condições com base na data da última modificação ou no ETag. O download ocorre apenas se as condições forem atendidas; caso contrário, o sistema retorna um erro. O download condicional reduz a transferência de dados pela rede e o consumo de recursos.
Condições de download
O OSS oferece suporte às seguintes condições de download.
Use If-Modified-Since e If-Unmodified-Since em conjunto. Da mesma forma, combine If-Match e If-None-Match.
Obtenha o ETag chamando ossClient.getObjectMeta.
|
Parâmetro |
Descrição |
|
If-Modified-Since |
Baixa o objeto se o horário especificado for anterior à última modificação dele. Caso contrário, retorna 304 Not Modified. |
|
If-Unmodified-Since |
Baixa o objeto quando o horário informado for igual ou posterior à data de modificação dele. Se a condição não for atendida, retorna 412 Precondition Failed. |
|
If-Match |
Baixa o objeto se o ETag especificado corresponder ao ETag do objeto. Na ausência de correspondência, retorna 412 Precondition Failed. |
|
If-None-Match |
Baixa o objeto caso o ETag informado seja diferente do ETag atual. Se forem iguais, retorna 304 Not Modified. |
Observações de uso
Este tópico utiliza 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 mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais detalhes, consulte Configurar credenciais de acesso.
Este exemplo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Configuração do cliente.
O download condicional exige a permissão
oss:GetObject. Para saber mais, consulte Conceder uma política personalizada.
Exemplos
O código a seguir baixa um objeto condicionalmente usando ossClient.getObject. Também é possível usar ossClient.downloadFile de maneira 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 mais informações sobre a operação de API usada para downloads condicionais, consulte GetObject.