Al descargar un solo objeto de un bucket, puede especificar condiciones basadas en la hora de última modificación o en el ETag. Si se cumplen las condiciones, el objeto se descarga. De lo contrario, se devuelve un error. La descarga condicional reduce la transferencia de red y el consumo de recursos.
Condiciones de descarga
OSS admite las siguientes condiciones de descarga.
If-Modified-Since e If-Unmodified-Since se pueden usar juntos. If-Match e If-None-Match también se pueden combinar.
Obtenga el ETag al llamar a ossClient.getObjectMeta.
|
Parámetro |
Descripción |
|
If-Modified-Since |
Si la hora especificada es anterior a la hora de última modificación del objeto, este se descarga. En caso contrario, se devuelve 304 Not Modified. |
|
If-Unmodified-Since |
Cuando la hora indicada es igual o posterior a la de última modificación del objeto, la descarga se lleva a cabo. De no ser así, se devuelve 412 Precondition Failed. |
|
If-Match |
El objeto se descarga si el ETag especificado coincide con el ETag del mismo. Si no coinciden, se devuelve 412 Precondition Failed. |
|
If-None-Match |
Este parámetro permite descargar el objeto cuando el ETag indicado difiere del ETag actual. Si son iguales, se devuelve 304 Not Modified. |
Notas de uso
Este tema utiliza el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles con OSS, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información, consulte 配置访问凭证.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Client configuration.
La descarga condicional requiere el permiso
oss:GetObject. Para obtener más información, consulte Grant a custom policy.
Ejemplos
A continuación se muestra un código que descarga un objeto con condiciones mediante ossClient.getObject. También puede usar ossClient.downloadFile de manera similar.
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();
}
}
}
}
Referencias
Para obtener más información sobre la operación de API que puede llamar para ejecutar una descarga condicional, consulte GetObject.