Todos os produtos
Search
Central de documentação

Object Storage Service:Download objects based on the last modified time or ETags of objects

Última atualização: Sep 24, 2026

Ao baixar um objeto de um bucket do Object Storage Service (OSS), você pode especificar condições de download com base na data e hora da última modificação ou no ETag do objeto. Se as condições especificadas forem atendidas, o objeto é baixado. Caso contrário, o sistema retorna um erro e o objeto não é baixado. Dessa forma, você evita baixar o mesmo objeto repetidamente, o que reduz o tráfego de rede e o uso de recursos, além de melhorar a eficiência do download.

Pré-requisitos

  • Você enviou os objetos para o OSS. Para mais informações, consulte Upload objects.

  • Para baixar um objeto Archive, restaure o objeto ou ative o acesso em tempo real a objetos Archive no bucket que o armazena. Para mais informações, consulte Restore objects e Archive Direct Read.

  • Para baixar um objeto Cold Archive ou Deep Cold Archive, restaure o objeto. Para mais informações, consulte Restore objects.

  • Para usar um usuário do Resource Access Management (RAM) no download condicional, conceda a permissão oss:GetObject a esse usuário. Para mais informações, consulte Common examples of RAM policies.

Cenários

  • Atualização de recursos do aplicativo: o aplicativo baixa um objeto apenas quando detecta que o ETag do objeto mudou ou que a data e hora da última modificação foram atualizados. Isso minimiza o uso de dados e otimiza a experiência do usuário.

  • Sincronização de dados e backup incremental: apenas os objetos cujos ETags mudaram ou cuja data e hora da última modificação foram atualizados são sincronizados ou incluídos no backup. Isso reduz os custos de largura de banda e garante a atualidade e a consistência dos dados.

  • Compartilhamento e sincronização de objetos: você pode usar os ETags ou a data e hora da última modificação dos objetos para verificar se houve alterações e, em seguida, sincronizar apenas os objetos modificados. Isso acelera a colaboração no trabalho e reduz o consumo de dados.

Condições de download

A tabela a seguir descreve as condições de download de objetos disponíveis.

Cabeçalho

Descrição

If-Modified-Since

Se a data e hora especificadas neste cabeçalho forem anteriores à data e hora da última modificação do objeto ou forem inválidas, o sistema retorna o objeto e o código 200 OK. Caso contrário, o sistema retorna o código 304 Not Modified.

O horário deve estar no formato GMT. Exemplo: Fri, 13 Nov 2015 14:47:53 GMT.

Por padrão, este cabeçalho é deixado em branco.

If-Unmodified-Since

Se a data e hora especificadas neste cabeçalho forem iguais ou posteriores à data e hora da última modificação do objeto, o sistema retorna o objeto e o código 200 OK. Caso contrário, o sistema retorna o código 412 Precondition Failed.

O horário deve estar no formato GMT. Exemplo: Fri, 13 Nov 2015 14:47:53 GMT.

Você pode especificar os cabeçalhos If-Modified-Since e If-Unmodified-Since na mesma solicitação.

Por padrão, este cabeçalho é deixado em branco.

If-Match

Se o ETag especificado neste cabeçalho corresponder ao ETag do objeto, o sistema retorna o objeto e o código 200 OK. Caso contrário, o sistema retorna o código 412 Precondition Failed.

O ETag de um objeto verifica a integridade dos dados do objeto.

Por padrão, este cabeçalho é deixado em branco.

If-None-Match

Se o ETag especificado neste cabeçalho não corresponder ao ETag do objeto, o sistema retorna o objeto e o código 200 OK. Caso contrário, o sistema retorna o código 304 Not Modified.

Você pode especificar os cabeçalhos If-Match e If-None-Match na mesma solicitação.

Por padrão, este cabeçalho é deixado em branco.

Importante

Não é possível fazer o download condicional pelo console do OSS ou pelo ossutil.

Procedimento

Usar SDKs do OSS

O código de exemplo a seguir mostra como fazer o download condicional usando o SDK do OSS para linguagens de programação comuns ao chamar GetObject. Para mais informações sobre como fazer o download condicional usando SDKs do OSS para outras linguagens de programação, consulte 简介.

Java

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

PHP

<?php

// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description of command line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. (Required)
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. (Optional)
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. (Required)
    "key" => ['help' => 'The name of the object', 'required' => True], // The object name. (Required)
];

// Convert the parameter description to the long option format required by getopt.
// A colon ":" after each parameter indicates that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters exist.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the parameter.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required parameter is missing, exit the program.
    }
}

// Extract values from the parsed parameters.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Assume that the last modified time of the object is 18:43:02 on October 21, 2024. If the specified UTC time is earlier than this time, the IfModifiedSince condition is met and the download is triggered.
$ifModifiedSince = "Sun, 21 Oct 2024 18:43:02 GMT";

// Assume that the ETag is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855. If the specified ETag is the same as the ETag of the object, the IfMatch condition is met and the download is triggered.
$etag = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(
            bucket: $bucket,
            key: $key,
            ifModifiedSince: $ifModifiedSince,
            ifMatch: $etag);

// Execute the get object operation.
$result = $client->getObject($request);

// Print the result.
// Output the HTTP status code, request ID, and object content.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL . // The request ID, which is used for debugging or tracking requests.
    'object content:' . $result->body->getContents() . PHP_EOL // The object content.
);

Node.js

const OSS = require('ali-oss');

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name.
  bucket: 'examplebucket'
});

async function main() {
  try {
    // Upload a file named exampleobject.txt to the destination bucket. You can customize the file content.
    await client.put("exampleobject.txt", Buffer.from("contenttest"));
    // Specify a time in the If-Modified-Since request header. The object is downloaded if the specified time is earlier than the actual modification time of the object.
    let result = await client.get("exampleobject.txt", {
      headers: {
        "If-Modified-Since": new Date("1970-01-01").toGMTString(),
      },
    });
    console.log(result.content.toString() === "contenttest");
    console.log(result.res.status === 200);

    // If the specified time is the same as or later than the actual modification time of the object, a 304 Not Modified error is returned.
    result = await client.get("exampleobject.txt", {
      headers: {
        "If-Modified-Since": new Date().toGMTString(),
      },
    });
    console.log(result.content.toString() === "");
    console.log(result.res.status === 304);
  } catch (e) {
    console.log(e.code === "Not Modified");
  }
}

main();

Python

import argparse
import alibabacloud_oss_v2 as oss
from datetime import datetime, timezone

# Create a command-line argument parser and describe the purpose of the script: get object and save to file sample.
parser = argparse.ArgumentParser(description="get object to file sample")

# Add the --region command-line argument to specify the region in which the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument to specify the name of the bucket from which to get the object. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument to specify the domain name that other services can use to access OSS. This argument is not required.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument to specify the key of the object (file) in OSS. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Add the --file_path command-line argument to specify the local path of the downloaded file. This argument is required.
parser.add_argument('--file_path', help='The path of the file to save the downloaded content.', required=True)

def main():
    # Parse the command-line arguments to get the user-input values.
    args = parser.parse_args()

    # Load the credentials required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    
    # Set the region property of the configuration object based on the command-line arguments.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property of the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client to interact with OSS.
    client = oss.Client(cfg)

    # Define the if_modified_since time.
    # Only objects modified after this time are returned.
    if_modified_since = datetime(2024, 10, 1, 12, 0, 0, tzinfo=timezone.utc)

    # Assume that the ETag is DA5223EFCD7E0353BE08866700000000. If the specified ETag is the same as the ETag of the object, the IfMatch condition is met and the download is triggered.
    etag = "\"DA5223EFCD7E0353BE08866700000000\""

    # Execute the request to get the object and save it to a local file.
    result = client.get_object_to_file(
        oss.GetObjectRequest(
            bucket=args.bucket,  # Specify the bucket name.
            key=args.key,        # Specify the object key.
            if_modified_since=if_modified_since,  # Only objects modified after the specified time are returned.
            if_match=etag,       # Only objects with a matching ETag are returned.
        ),
        args.file_path  # Specify the local path to which the file is downloaded.
    )

    # Print the result of getting the object, including the status code and request ID.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content length: {result.content_length},'
          f' content range: {result.content_range},'
          f' content type: {result.content_type},'
          f' etag: {result.etag},'
          f' last modified: {result.last_modified},'
          f' content md5: {result.content_md5},'
          f' cache control: {result.cache_control},'
          f' content disposition: {result.content_disposition},'
          f' content encoding: {result.content_encoding},'
          f' expires: {result.expires},'
          f' hash crc64: {result.hash_crc64},'
          f' storage class: {result.storage_class},'
          f' object type: {result.object_type},'
          f' version id: {result.version_id},'
          f' tagging count: {result.tagging_count},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' next append position: {result.next_append_position},'
          f' expiration: {result.expiration},'
          f' restore: {result.restore},'
          f' process status: {result.process_status},'
          f' delete marker: {result.delete_marker},'
          f' server time: {result.headers.get("x-oss-server-time")},'
    )

# When this script is run directly, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts from here.

Browser.js

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>
</head>

<body>
  <button id='upload'>Upload</button>
  <button id='download'>Download</button>
    <!--Import the SDK file.-->
  <script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js"></script>
  <script type="text/javascript">
      const client = new OSS({
         // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
         region: 'yourRegion',
         authorizationV4: true,
         // The temporary AccessKey ID and AccessKey secret obtained from Security Token Service (STS).
         accessKeyId: 'yourAccessKeyId',
         accessKeySecret: 'yourAccessKeySecret',
         // The SecurityToken obtained from STS.
        stsToken: 'yourSecurityToken',
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
      });

    const download = document.getElementById('download')
    const upload = document.getElementById('upload')

    // Upload the file.  
    upload.addEventListener('click', () => {
      // Specify the content of the file to upload.
      const file = new Blob(['examplecontent'])
      // Specify the full path of the file to upload. For example, exampledir/exampleobject.txt.
      const fileName = 'exampledir/exampleobject.txt'
      const result = client.put(fileName, file).then(r => console.log(r))
    })

    // Download the file.
    download.addEventListener('click', () => {
      // Specify the byte range to download.
      const start = 1, end = 5
      client.get('exampledir/exampleobject.txt', {
        headers: {
          // Specify a time in the If-Modified-Since request header. The file is downloaded if the specified time is earlier than the actual modification time of the file. If the specified time is the same as or later than the actual modification time, 304 Not Modified is returned.
          "If-Modified-Since": new Date("1970-01-01").toGMTString()
          // Specify a time in the If-Unmodified-Since request header. The file is downloaded if the specified time is the same as or later than the actual modification time of the file. If the specified time is earlier than the actual modification time, 412 Precondition Failed is returned.
          //"If-Unmodified-Since": new Date(1970-01-01).toGMTString()
          // Specify an ETag in the If-Match request header. The file is downloaded if the specified ETag matches the ETag of the file. If the specified ETag does not match, 412 Precondition Failed is returned.
          //"If-Match": '5B3C1A2E0563E1B002CC607C****'
          // Specify an ETag in the If-None-Match request header. The file is downloaded if the specified ETag does not match the ETag of the file. If the specified ETag matches, 304 Not Modified is returned.
          //"If-None-Match": '5B3C1A2E0563E1B002CC607C****'
        },
      }).then(r => {
        if (r.content.length > 0) {                
          const newBlob = new Blob([r.content], { type: r.res.headers['content-type'] });
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(newBlob)
          link.download = 'foo.txt'
          link.click()
          window.URL.revokeObjectURL(link.href)
        } else {
          console.log('Error code', r.res.status)
          console.log('No items to download that meet the conditions')
        }
      })
    })

  </script>
</body>

</html>

Android

// Set the bucket name, such as examplebucket, and the full path of the object, such as exampledir/exampleobject.txt.
// The full path of the object cannot contain the bucket name.
String bucketName = "examplebucket";
String objectKey = "exampledir/exampleobject.txt";
// Create a request to download the object.
Map<String, String> headers = new HashMap<>();
// If the specified time is earlier than the object's last modification time, the object is downloaded. Otherwise, a 304 Not modified error is returned.
headers.put(OSSHeaders.GET_OBJECT_IF_MODIFIED_SINCE, "Fri, 13 Nov 2015 14:47:53 GMT");
// If the specified time is the same as or later than the object's last modification time, the object is downloaded. Otherwise, a 412 Precondition failed error is returned.
// headers.put(OSSHeaders.GET_OBJECT_IF_UNMODIFIED_SINCE, "Fri, 13 Nov 2015 14:47:53 GMT");
// If the specified ETag matches the object's ETag, the object is downloaded. Otherwise, a 412 Precondition failed error is returned.
// headers.put(OSSHeaders.GET_OBJECT_IF_MATCH, "5B3C1A2E0563E1B002CC607C*****");
// If the specified ETag does not match the object's ETag, the object is downloaded. Otherwise, a 304 Not modified error is returned.
// headers.put(OSSHeaders.GET_OBJECT_IF_NONE_MATCH, "5B3C1A2E0563E1B002CC607C*****");
GetObjectRequest get = new GetObjectRequest(bucketName, objectKey);
get.setRequestHeaders(headers);

OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
    @Override
    public void onSuccess(GetObjectRequest request, GetObjectResult result) {
        // The request is successful.
        InputStream inputStream = result.getObjectContent();
        byte[] buffer = new byte[2048];
        int len;
        try {
            while ((len = inputStream.read(buffer)) != -1) {
                // Process the downloaded data.
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // The request failed.
        if (clientExcepion != null) {
            // A client exception occurred, such as a network exception.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A service exception occurred.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Go

package main

import (
	"context"
	"flag"
	"log"
	"net/http"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Use the init function to initialize parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Specify the path of the local file.
	localFile := "download.file"

	// For example, an object was last modified at 18:43:02, November 21, 2023. If the time specified in the IfModifiedSince condition is earlier than the last modified time, the object is downloaded. 
	date := time.Date(2024, time.October, 21, 18, 43, 2, 0, time.UTC)

	// Assume that the ETag of an object is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855. If the ETag specified in the IfMatch condition matches the ETag of the object, the object is downloaded. 
	etag := "\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\""

	// Create a request to download the object.
	getRequest := &oss.GetObjectRequest{
		Bucket:          oss.Ptr(bucketName),                   // The name of the bucket.
		Key:             oss.Ptr(objectName),                   // The name of the object.
		IfModifiedSince: oss.Ptr(date.Format(http.TimeFormat)), // Specify the IfModifiedSince condition.
		IfMatch:         oss.Ptr(etag),                         // Specify the IfMatch condition.
	}

	// Download the object to a local device and process the result.
	result, err := client.GetObjectToFile(context.TODO(), getRequest, localFile)
	if err != nil {
		log.Fatalf("failed to get object to file %v", err)
	}

	log.Printf("get object to file result:%#v\n", result)
}

iOS

OSSGetObjectRequest *get = [OSSGetObjectRequest new];
// Specify the name of the bucket. For more information about bucket naming, see Bucket naming conventions. 
get.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path of the object. For more information about the naming conventions for objects, see Object naming conventions. 
get.objectKey = @"exampledir/exampleobject.txt";
NSMutableDictionary *headerFields = [NSMutableDictionary dictionary];
// Set If-Modified-Since to Fri, 13 Oct 2021 14:47:53 GMT. 
[headerFields setValue:@"Fri, 13 Oct 2021 14:47:53 GMT" forKey:@"If-Modified-Since"];
// Specify that the object is downloaded only when its last modified time is the specified time or earlier. 
[headerFields setValue:[[NSDate new] oss_asStringValue] forKey:@"If-Unmodified-Since"];
// Specify that the object is downloaded only if its entity tag (ETag) is not the specified ETag. 
[headerFields setValue:@"5B3C1A2E0563E1B002CC607C****" forKey:@"If-None-Match"];
// Specify that the object is downloaded only if its ETag is the same as the specified ETag. 
[headerFields setValue:@"fba9dede5f27731c9771645a3986****" forKey:@"If-Match"];
get.headerFields = headerFields;

[[[client getObject:get] continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
    if (!task.error) {
        NSLog(@"get object success!");
    } else {
        NSLog(@"get object error: %@", task.error);
    }
    return nil;
}] waitUntilFinished];

Usar a API do OSS

Se o seu caso de uso exige um alto nível de personalização, você pode chamar as APIs RESTful diretamente. Para chamar uma API diretamente, inclua o cálculo da assinatura no seu código. Para mais informações, consulte GetObject.

Referências

  • Para mais informações sobre como baixar um objeto de um bucket com versionamento ativado, consulte Manage versioned objects.

  • Para mais informações sobre como baixar um objeto de um bucket com versionamento suspenso, consulte Manage objects in a versioning-suspended bucket.

  • O OSS permite configurar listas de controle de acesso (ACLs) para buckets e objetos. Dessa forma, usuários externos não autorizados não podem baixar dados do seu bucket. Para mais informações, consulte Overview.

  • Para baixar um objeto diretamente de um bucket, use o download simples. Para mais informações, consulte Simple download.

  • Para retomar tarefas de download interrompidas a partir do ponto de interrupção ao baixar objetos grandes, use o download retomável. Para mais informações, consulte Resumable download.

  • Para conceder permissões a usuários externos e permitir que baixem objetos de um bucket com ACL privada, use o Security Token Service (STS) para gerar credenciais de acesso temporárias ou use URLs assinadas. Para mais informações, consulte Authorize third-party users to download objects.