Use o OSS Android SDK para criar buckets, fazer upload de objetos e baixar objetos.
Pré-requisitos
O Android SDK está instalado. Instalação (Android SDK).
Projeto de exemplo
Os campos OSS_ACCESS_KEY_ID e OSS_ACCESS_KEY_SECRET na classe Config do projeto de exemplo servem apenas para depuração local e verificação de funcionalidades. Nunca codifique permanentemente um par de AccessKey em um aplicativo móvel de produção. Em ambientes de produção, adote uma das seguintes abordagens:
Transferência direta pelo cliente: o aplicativo móvel obtém uma credencial temporária STS do servidor de aplicações e a usa para inicializar um OSSClient. Para obter instruções de configuração, consulte Configurar transferência direta de dados para aplicativos móveis.
URLs pré-assinadas geradas pelo servidor: o servidor de aplicações gera URLs pré-assinadas e as fornece ao aplicativo móvel, que faz upload ou download via HTTP padrão sem armazenar credenciais. Essa abordagem é recomendada para dados sensíveis à privacidade, como documentos de identidade, imagens faciais e credenciais de pagamento. Para mais detalhes, consulte Autorizar acesso (Android SDK).
Para usar o projeto de exemplo:
Consulte o diretório de exemplos para visualizar casos de upload de arquivos locais, download de objetos, uploads retomáveis e callbacks.
Clone o projeto com o Git.
Antes de executar este projeto, configure os parâmetros no arquivo 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;
}
Para configurar a URL do servidor de autenticação STS, siga as etapas em Criar rapidamente um service de upload direto para aplicativos móveis.
O script sts_local_server está disponível no GitHub.
Para criar um par de AccessKey, consulte Criar um par de AccessKey.
Criar um bucket
Um bucket é um namespace globalmente exclusivo no OSS que armazena qualquer quantidade de objetos.
// 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());
}
}
});
Fazer upload de um objeto
Faça upload de um arquivo local para o OSS como um objeto:
// 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.
Baixar um objeto
Baixe um objeto do OSS para um arquivo 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();