Todos los productos
Search
Centro de documentos

Object Storage Service:Validación de datos (SDK para Android)

Última actualización: Sep 22, 2026

El SDK de Object Storage Service (OSS) para Android proporciona métodos que permiten comprobar la integridad de los datos y garantizar su seguridad cuando se cargan, descargan o copian objetos.

Notas de uso

  • Antes de ejecutar el código de ejemplo de este tema, cree una instancia de OSSClient con métodos como el uso de un nombre de dominio personalizado o Security Token Service (STS). Para obtener más información, consulte Initialization (Android SDK).

Contexto

Debido a la complejidad del entorno de las redes móviles, puede producirse un error durante la transferencia de datos entre el cliente y el servidor. El SDK de OSS para Android ofrece los métodos de verificación CRC-64 y MD5 para garantizar la integridad de los datos.

Comprobación de redundancia cíclica

Si habilita la verificación CRC-64 para la lectura del flujo de datos, OSS comprueba automáticamente la integridad de los datos al finalizar dicha lectura.

A continuación se muestra un ejemplo de código sobre cómo habilitar CRC-64:

Nota

En este ejemplo se utiliza la operación síncrona getObject. Las operaciones síncronas deben ejecutarse en un hilo secundario.

// Specify the bucket name, such as examplebucket, and the full path of the object, such as exampledir/exampleobject.txt.
// Do not include the bucket name in the full path of the object.
String bucketName = "examplebucket";
String objectKey = "exampledir/exampleobject.txt";
GetObjectRequest request = new GetObjectRequest(bucketName, objectKey);
// Enable CRC-64 validation.
request.setCRC64(OSSRequest.CRC64Config.YES);
try{
    GetObjectResult result = oss.getObject(request);
    InputStream in = result.getObjectContent();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[2048];
    int len;
    while ((len = in.read(buffer)) > -1) {
        output.write(buffer, 0, len);
    }
    output.flush();
    in.close();
} catch (ServiceException e) {
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("RequestId", e.getRequestId());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
} catch (ClientException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Verificación MD5

Para comprobar si el objeto que cargó mediante una carga multiparte es idéntico al archivo local, cargue las partes con el valor Content-MD5 especificado en la solicitud de carga. OSS verifica la consistencia del valor MD5 para garantizar la integridad de los datos. La carga es exitosa únicamente si el hash MD5 del objeto que recibe el servidor de OSS coincide con el valor Content-MD5. Este método garantiza la consistencia del objeto cargado.

A continuación se muestra un ejemplo de código sobre cómo habilitar la verificación MD5:

// Specify the bucket name, such as examplebucket, the full path of the object, such as exampledir/exampleobject.txt, and the full path of the local file, such as /storage/emulated/0/oss/examplefile.txt.
// Do not include the bucket name in the full path of the object.
String bucketName = "examplebucket";
String objectKey = "exampledir/exampleobject.txt";
String filePath = "/storage/emulated/0/oss/examplefile.txt";
// Construct an upload request.
ObjectMetadata metadata = new ObjectMetadata();
try {
    // Calculate the Base64-encoded MD5 hash.
    String fileMD5 = BinaryUtil.calculateBase64Md5(filePath);
    Log.i("oss", "file md5: " + fileMD5);
    metadata.setContentMD5(fileMD5);
} catch (IOException e) {
    Log.e("oss", "Calculate file md5 error: " + e.getMessage());
}
PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, filePath);
put.setMetadata(metadata);

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) {
        // Handle request exceptions.
        if (clientExcepion != null) {
            // Handle client-side exceptions, such as network errors.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle server-side exceptions.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Referencias

  • Para obtener más información sobre cómo inicializar una instancia de OSSClient, consulte Initialization.