Todos os produtos
Search
Central de documentação

Object Storage Service:Object tagging (Android SDK)

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) permite configurar tags em objetos para classificá-los. Este tópico descreve como adicionar tags a um objeto, consultar as tags de um objeto e excluir as tags de um objeto.

Observações de uso

  • Antes de executar o código de exemplo deste tópico, crie uma instância OSSClient usando métodos como nome de domínio personalizado ou Security Token Service (STS). Para mais informações, consulte Inicialização (Android SDK).

Configure tags de objetos

Adicionar tags a um objeto durante o upload

Nota

Se já existir um objeto com o mesmo nome no caminho especificado, o upload substituirá o objeto existente. Caso não queira sobrescrever o objeto existente, configure os parâmetros adequados. Para mais informações, consulte Impedir que objetos sejam substituídos por objetos com o mesmo nome.

O código de exemplo a seguir demonstra como adicionar tags a um objeto durante o upload:

// Create an upload request.
// Specify the bucket name, the full path of the object, and the full path of the local file. For example, examplebucket, exampledir/exampleobject.txt, and /storage/emulated/0/oss/examplefile.txt.
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");
Map<String, String> tags = new HashMap<String, String>();
// Set the tag information.
tags.put("key1", "value1");
tags.put("Key2", "value2");
String tagHeader = OSSUtils.paramToQueryString(tags, "UTF-8");

ObjectMetadata metadata = new ObjectMetadata();
metadata.setHeader("x-oss-tagging", tagHeader);
put.setMetadata(metadata);

// Set a callback to track the progress of an asynchronous upload.
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
    @Override
    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Request exception.
        if (clientExcepion != null) {
            // Client exception, such as a network exception.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Server exception.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Adicionar ou modifique tags de um objeto existente

O exemplo de código a seguir ilustra como adicionar novas tags ou alterar as tags de um objeto existente:

// Specify the bucket name. For example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. For example, exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";

Map<String, String> tags = new HashMap<String, String>();
// Set the tag information.
tags.put("owner", "John");
tags.put("type", "document");

PutObjectTaggingRequest putObjectTaggingRequest = new PutObjectTaggingRequest(bucketName, objectName, tags);
oss.asyncPutObjectTagging(putObjectTaggingRequest, new OSSCompletedCallback<PutObjectTaggingRequest, PutObjectTaggingResult>() {
    @Override
    public void onSuccess(PutObjectTaggingRequest request, PutObjectTaggingResult result) {
        Log.d("PutTagging", "PutTaggingSuccess");
    }

    @Override
    public void onFailure(PutObjectTaggingRequest request, ClientException clientException, ServiceException serviceException) {
        // Request exception.
        if (clientException != null) {
            // Client exception, such as a network exception.
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // Server exception.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Adicionar tags ao copiar um objeto

Para aplicar tags durante a cópia de um objeto, use o seguinte código de exemplo:

// Create a CopyObject request.
// Specify the source bucket name, the full path of the source object, the destination bucket name, and the full path of the destination object. For example, examplebucket, exampledir/exampleobject.txt, destexamplebucket, and destexampledir/exampleobject.txt.
// The full path of the object cannot contain the bucket name.
CopyObjectRequest copyObjectRequest = new CopyObjectRequest("examplebucket", "exampledir/exampleobject.txt",
        "destexamplebucket", "destexampledir/exampleobject.txt");
ObjectMetadata objectMetadata = new ObjectMetadata();
Map<String, String> tags = new HashMap<String, String>();
// Set tags for the destination object.
tags.put("key1", "value1");
tags.put("key2", "value2");
String tagHeader = OSSUtils.paramToQueryString(tags, "UTF-8");
objectMetadata.setHeader("x-oss-tagging", tagHeader);
// Ignore the tags of the source object and use the tags specified in the request.
objectMetadata.setHeader("x-oss-tagging-directive", "REPLACE");
copyObjectRequest.setNewObjectMetadata(objectMetadata);

OSSAsyncTask copyTask = oss.asyncCopyObject(copyObjectRequest, new OSSCompletedCallback<CopyObjectRequest, CopyObjectResult>() {
    @Override
    public void onSuccess(CopyObjectRequest request, CopyObjectResult result) {
        Log.d("copyObject", "copy success!");
    }

    @Override
    public void onFailure(CopyObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Request exception.
        if (clientExcepion != null) {
            // Client exception, such as a network exception.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Service exception.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Adicionar tags a um link simbólico

Este exemplo mostra como defina tags em um link simbólico:

PutSymlinkRequest putSymlink = new PutSymlinkRequest();
// Specify the bucket name. For example, examplebucket.
putSymlink.setBucketName("examplebucket");
// Set the name of the symbolic link.
putSymlink.setObjectKey("yourSymLink");
// Set the name of the object file.
putSymlink.setTargetObjectName("yourTargetObjectName");

Map<String, String> tags = new HashMap<String, String>();
// Set the tag information.
tags.put("key1", "value1");
tags.put("key2", "value2");
String tagHeader = OSSUtils.paramToQueryString(tags, "UTF-8");
ObjectMetadata metadata = new ObjectMetadata();
metadata.setHeader("x-oss-tagging", tagHeader);
putSymlink.setMetadata(metadata);

OSSAsyncTask task = oss.asyncPutSymlink(putSymlink, new OSSCompletedCallback<PutSymlinkRequest,
        PutSymlinkResult>() {
    @Override
    public void onSuccess(PutSymlinkRequest request, PutSymlinkResult result) {
        OSSLog.logInfo("code:"+result.getStatusCode());

    }

    @Override
    public void onFailure(PutSymlinkRequest request, ClientException clientException,
                          ServiceException serviceException) {
        OSSLog.logError("error: "+serviceException.getRawMessage());

    }
});

Consultar tags de um objeto

Use o código a seguir para obter as tags associadas a um objeto:

// Specify the bucket name. For example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. For example, exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Get the tags of the object.
GetObjectTaggingRequest getObjectTaggingRequest = new GetObjectTaggingRequest(bucketName, objectName);
oss.asyncGetObjectTagging(getObjectTaggingRequest, new OSSCompletedCallback<GetObjectTaggingRequest, GetObjectTaggingResult>() {
    @Override
    public void onSuccess(GetObjectTaggingRequest request, GetObjectTaggingResult result) {
        for (Map.Entry<String, String> s : result.getTags().entrySet()) {
            Log.d("tag", "key: " + s.getKey() + ", value: " + s.getValue());
        }
    }

    @Override
    public void onFailure(GetObjectTaggingRequest request, ClientException clientException, ServiceException serviceException) {
        // Request exception.
        if (clientException != null) {
            // Client exception, such as a network exception.
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // Server exception.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Exclua tags de um objeto

Para remover todas as tags de um objeto, execute o seguinte código:

// Specify the bucket name. For example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. For example, exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Delete the tags of the object.
DeleteObjectTaggingRequest deleteObjectTaggingRequest = new DeleteObjectTaggingRequest(bucketName, objectName);
oss.asyncDeleteObjectTagging(deleteObjectTaggingRequest, new OSSCompletedCallback<DeleteObjectTaggingRequest, DeleteObjectTaggingResult>() {
    @Override
    public void onSuccess(DeleteObjectTaggingRequest request, DeleteObjectTaggingResult result) {
        Log.d("deleteTagging", "deleteTagging success");
    }

    @Override
    public void onFailure(DeleteObjectTaggingRequest request, ClientException clientException, ServiceException serviceException) {
        // Request exception.
        if (clientException != null) {
            // Client exception, such as a network exception.
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // Server exception.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Referências