Tous les produits
Search
Centre de documentation

Object Storage Service:Démarrage rapide (SDK Android)

Dernière mise à jour :Aug 18, 2026

Utilisez le SDK OSS pour Android afin de créer des buckets, de charger des objets et de les télécharger.

Prérequis

Le SDK Android est installé. Installation (SDK Android).

Exemple de projet

Important

Les champs OSS_ACCESS_KEY_ID et OSS_ACCESS_KEY_SECRET de la classe Config de l'exemple de projet sont destinés uniquement au débogage local et à la vérification des fonctionnalités. Ne codez jamais en dur une paire AccessKey à long terme dans une application mobile de production. En production, utilisez l'une des approches suivantes :

  • Transfert direct côté client : l'application mobile récupère un identifiant temporaire STS depuis votre serveur d'application et l'utilise pour initialiser un OSSClient. Pour obtenir des instructions de configuration, consultez la rubrique Configurer le transfert direct de données pour les applications mobiles.

  • URL présignées générées par le serveur : votre serveur d'application génère des URL présignées et les transmet à l'application mobile, qui effectue les chargements ou téléchargements via HTTP standard sans jamais détenir d'identifiant. Cette méthode est recommandée pour les données sensibles telles que les cartes d'identité, les images faciales et les informations de paiement. Pour plus de détails, consultez la rubrique Autoriser l'accès (SDK Android).

Pour utiliser l'exemple de projet :

  • Consultez le répertoire d'exemples pour voir des exemples de chargement de fichiers locaux, de téléchargement d'objets, de chargements repris et de rappels.

  • Clonez le projet à l'aide de Git.

Avant d'exécuter ce projet, configurez les paramètres dans le fichier Config :

public class Config {    

    // In this example, the endpoint for the China (Hangzhou) region is used. Specify the endpoint for your region.
    public static final String OSS_ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";
    // Specify the callback URL.
    public static final String OSS_CALLBACK_URL = "https://oss-demo.aliyuncs.com:23450";
    // Specify the URL of the STS authentication server.
    // You can also start a local STS authentication server based on the script in the project's sts_local_server directory.
    public static final String STS_SERVER_URL = "http://****/sts/getsts";
    
    public static final String BUCKET_NAME = "yourBucketName";
    public static final String OSS_ACCESS_KEY_ID = "yourAccessKeyId";;
    public static final String OSS_ACCESS_KEY_SECRET = "yourAccessKeySecret";

    public static final int DOWNLOAD_SUC = 1;
    public static final int DOWNLOAD_Fail = 2;
    public static final int UPLOAD_SUC = 3;
    public static final int UPLOAD_Fail = 4;
    public static final int UPLOAD_PROGRESS = 5;
    public static final int LIST_SUC = 6;
    public static final int HEAD_SUC = 7;
    public static final int RESUMABLE_SUC = 8;
    public static final int SIGN_SUC = 9;
    public static final int BUCKET_SUC = 10;
    public static final int GET_STS_SUC = 11;
    public static final int MULTIPART_SUC = 12;
    public static final int STS_TOKEN_SUC = 13;
    public static final int FAIL = 9999;
    public static final int REQUESTCODE_AUTH = 10111;
    public static final int REQUESTCODE_LOCALPHOTOS = 10112;
}

Créer un bucket

Un bucket est un espace de noms globalement unique dans OSS qui stocke n'importe quel nombre d'objets.

// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// Set region to the region where your bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
String region = "yourRegion";
// The temporary AccessKey pair (AccessKey ID and AccessKey Secret) obtained from an STS authentication server.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from an STS authentication server.
String securityToken = "yourSecurityToken";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

// Specify the bucket name.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("bucketName");
// Set the access control list (ACL) of the bucket to public read. The default ACL is private.
createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead);
// Specify the region where the bucket is located.
createBucketRequest.setLocationConstraint("oss-cn-hangzhou");
OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
    @Override
    public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
        Log.d("locationConstraint", request.getLocationConstraint());
        }
    @Override
    public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
        // The request failed.
        if (clientException != null) {
            // Client exception, such as a network error.
            clientException.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());
        }
    }
});

Charger un objet

Chargez un fichier local vers OSS en tant qu'objet :

// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// Set region to the region where your bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
String region = "yourRegion";
// The temporary AccessKey pair (AccessKey ID and AccessKey Secret) obtained from an STS authentication server.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from an STS authentication server.
String securityToken = "yourSecurityToken";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);

// Create an upload request.
PutObjectRequest put = new PutObjectRequest("<bucketName>", "<objectName>", "<uploadFilePath>");

// You can set a progress callback for asynchronous uploads.
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) {
        // The request failed.
        if (clientExcepion != null) {
            // Client exception, such as a network error.
            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());
        }
    }
});
// task.cancel(); // You can cancel the task.
// task.waitUntilFinished(); // Wait until the upload is complete.

Télécharger un objet

Téléchargez un objet depuis OSS vers un fichier local :

// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// The temporary AccessKey pair (AccessKey ID and AccessKey Secret) obtained from an STS authentication server.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from an STS authentication server.
String securityToken = "yourSecurityToken";
// Set region to the region where your bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
String region = "yourRegion";

OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);
// Create a download request.
GetObjectRequest get = new GetObjectRequest("<bucketName>", "<objectName>");

OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
    @Override
    public void onSuccess(GetObjectRequest request, GetObjectResult result) {
        // The request was successful.
        Log.d("asyncGetObject", "DownloadSuccess");
        Log.d("Content-Length", "" + result.getContentLength());

        InputStream inputStream = result.getObjectContent();
        byte[] buffer = new byte[2048];
        int len;

        try {
            while ((len = inputStream.read(buffer)) != -1) {
                // Add your code here to 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) {
            // Client exception, such as a network error.
            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());
        }
    }
});
// Cancel the task.
// task.cancel(); 
// Wait for the task to complete.
// task.waitUntilFinished();