Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciar metadados de objetos (OSS SDK for Java 1.0)

Última atualização: Jul 03, 2026

Os objetos armazenados no Object Storage Service (OSS) consistem em chaves, dados e metadados. Os metadados descrevem os atributos do objeto e incluem cabeçalhos HTTP padrão e metadados de usuário. Configure cabeçalhos HTTP padrão para criar políticas personalizadas de requisição HTTP, como políticas de cache e de download forçado de objetos. Também é possível configurar metadados de usuário para identificar a finalidade ou os atributos de um objeto.

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 detalhes sobre as regiões e endpoints compatíveis, consulte Regiões e endpoints.

  • As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configuração do cliente.

  • Para configurar metadados de objetos, você deve ter a permissão oss:PutObject. Para consultar metadados de objetos, você deve ter a permissão oss:GetObject. Para mais informações, consulte Conceder uma política personalizada.

Configurar metadados de objetos

Os exemplos de código a seguir mostram como configurar cabeçalhos HTTP padrão e metadados de usuário.

  • Configurar cabeçalhos HTTP padrão

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    import com.aliyun.oss.common.utils.BinaryUtil;
    import com.aliyun.oss.common.utils.DateUtil;
    import com.aliyun.oss.model.ObjectMetadata;
    import java.io.ByteArrayInputStream;
    
    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 bucket name. 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 content = "Hello OSS";
            // 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 {
                // Add metadata for the uploaded object. 
                ObjectMetadata meta = new ObjectMetadata();
    
                String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(content.getBytes()));
                // Enable MD5 verification. After MD5 verification is enabled, OSS calculates the MD5 hash of the uploaded object and compares this MD5 hash with that specified in the request. If the two values are different, an error is reported. 
                meta.setContentMD5(md5);
                // Specify the type of content to upload. The browser determines the format and encoding type that are used to read the object based on the content type of the object. If the content type is not specified, a content type is generated based on the object name extension. If no extension is available, the default value application/octet-stream is used as the content type. 
                meta.setContentType("text/plain; charset=utf-8");
                // Configure the headers. For example, specify the storage class for uploaded files.
                meta.setHeader("x-oss-storage-class", StorageClass.Standard);
                
                // To enable the following configurations as needed, uncomment the corresponding lines.
                
                // Specify a name for the object when the content is downloaded. 
                // meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
                // Specify the length of the object to upload. If the actual object length is greater than the specified length, the object is truncated. Only the content of the specified length is uploaded. If the actual object length is smaller than the specified length, all content of the object is uploaded. 
                // meta.setContentLength(content.length());
                // Specify the caching behavior of the web page when the content is downloaded. 
                // meta.setCacheControl("Download Action");
                // Specify the expiration time of the cache in UTC. 
                // meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
                // Specify the content encoding format when the content is downloaded. 
                // meta.setContentEncoding("gzip");
    
                // Upload the object. 
                ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), meta);
            } 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();
                }
            }
        }
    }               

    Para mais informações sobre cabeçalhos HTTP, consulte RFC 2616.

  • Configurar metadados de usuário para descrever um objeto

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    import com.aliyun.oss.model.ObjectMetadata;
    import java.io.ByteArrayInputStream;
    
    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 bucket name. 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 content = "Hello OSS";
            // 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 {
                // Add metadata for the object. 
                ObjectMetadata meta = new ObjectMetadata();
                // Specify custom metadata. We recommend that you use the Base64 encoding method. 
                meta.addUserMetadata("key1", "value1");
                meta.addUserMetadata("key2", "value2");
    
                // Upload the object. 
                ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), meta);            
            } 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();
                }
            }
        }
    }                    

    Os metadados de um objeto são baixados junto com o objeto. Um objeto pode ter vários metadados, desde que o tamanho total não exceda 8 KB.

Modificar metadados de objetos

O exemplo de código a seguir mostra como modificar os metadados de um objeto:

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;

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 source bucket. 
        String sourceBucketName = "yourSourceBucketName";
        // Specify the full path of the source object. 
        String sourceObjectName = "yourSourceObjectName";
        // Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket. 
        String destinationBucketName = "yourDestinationBucketName";
        // Specify the full path of the destination object. 
        String destinationObjectName = "yourDestinationObjectName";
        // 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 {
            // Specify that the source object is the same as the destination object. Call the ossClient.copyObject method to modify the object metadata. 
            CopyObjectRequest request = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);

            ObjectMetadata meta = new ObjectMetadata();
            // Specify the type of content to upload. The browser determines the format and encoding type that are used to read the object based on the content type of the object. If the content type is not specified, a content type is generated based on the object name extension. If no extension is available, the default value application/octet-stream is used as the content type. 
            meta.setContentType("text/plain; charset=utf-8");
            // Configure the headers. For example, specify the storage class for uploaded files.
            meta.setHeader("x-oss-storage-class", StorageClass.Standard);
            
            // To enable the following configurations as needed, uncomment the corresponding lines.
            
            // Specify a name for the object when the content is downloaded. 
            // meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
            // Specify the length of the object that can be uploaded. If the actual object length is greater than the specified length, only the specified length of the content is uploaded and the trailing part is truncated. If the actual object length is smaller than the specified length, all content of the object is uploaded.
            // meta.setContentLength(content.length());
            // Specify the caching behavior of the web page when the content is downloaded. 
            // meta.setCacheControl("Download Action");
            // Specify the expiration time of the cache in UTC. 
            // meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
            // Specify the content encoding format when the content is downloaded. 
            // meta.setContentEncoding("gzip");
 
            // Specify custom metadata. We recommend that you use the Base64 encoding method. 
            meta.addUserMetadata("key1", "value1");
            meta.addUserMetadata("key2", "value2");
            
            request.setNewObjectMetadata(meta);

            // Modify the object metadata. 
            ossClient.copyObject(request);
        } 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();
            }
        }
    }
}            

Consultar metadados de objetos

A tabela a seguir lista os métodos disponíveis para consultar metadados de objetos.

Método

Descrição

ossClient.getSimplifiedObjectMeta

Consulta os valores de ETag, Size e LastModified do objeto chamando a operação GetObjectMeta.

ossClient.getObjectMetadata

Consulta todos os metadados do objeto chamando a operação HeadObject.

O exemplo de código a seguir mostra como consultar metadados de objetos:

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.SimplifiedObjectMeta;

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 bucket name. 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";
        // 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 {
            // Specify the bucket name and the full path of the object in the bucket. 
            // Query partial metadata of the object. 
            SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, objectName);
            System.out.println("Query partial metadata of the object");
            System.out.println(objectMeta.getSize());
            System.out.println(objectMeta.getETag());
            System.out.println(objectMeta.getLastModified());
            // Query object metadata, including the last access time of the object (X-Oss-Last-Access-Time), after the access tracking feature is enabled. You can only use OSS SDK for Java V3.16.0 or later to query X-Oss-Last-Access-Time. 
            System.out.println(objectMeta.getHeaders().get("x-oss-last-access-time"));

            // Query all metadata of the object. 
            ObjectMetadata metadata = ossClient.getObjectMetadata(bucketName, objectName);
            System.out.println("Query partial metadata of the object");
            System.out.println(metadata.getContentType());
            System.out.println(metadata.getLastModified());
            System.out.println(metadata.getExpirationTime());
            System.out.println(metadata.getETag());
            System.out.println(metadata.getContentMD5());
            System.out.println(metadata.getContentLength());
            System.out.println(metadata.getObjectType());
            System.out.println(metadata.getUserMetadata());
        } 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 metadados de objetos, consulte Gerenciar metadados de objetos.

  • Para obter o código de exemplo completo usado para configurar e consultar metadados de objetos, visite o GitHub.

  • Para mais informações sobre a operação de API usada para configurar metadados de objetos durante um upload simples, consulte PutObject.

  • Para mais informações sobre as operações de API usadas para consultar metadados de objetos, consulte GetObjectMeta e HeadObject.