このトピックでは、Object Storage Service (OSS) SDK for Androidを使用して、バケットの作成、オブジェクトのアップロード、オブジェクトのダウンロードなどの日常的な操作を実行する方法について説明します。
前提条件
OSS SDK for Androidがインストールされています。 詳細については、「インストール」をご参照ください。
サンプルプロジェクト
次の方法を使用して、サンプルプロジェクトを試すことができます。
ローカルファイルのアップロード、オブジェクトのダウンロード、再開可能なアップロードの実行、コールバックの設定のコード例を含むサンプルディレクトリを表示します。 詳細については、『GitHub』をご参照ください。
git cloneコマンドを実行して、プロジェクトを複製します。
プロジェクトを実行する前に、Configクラスを設定する必要があります。 次のサンプルコードは、Configクラスの設定方法の例を示しています。
public class Config {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
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 Security Token Service (STS) authentication server.
// You can also start the local STS authentication server by running the local authentication script in the sts_local_server directory of the project.
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;
}
STS認証サーバーのURLを設定する方法の詳細については、「モバイルアプリの直接データ転送の設定」をご参照ください。
sts_local_serverディレクトリのスクリプトの詳細については、『GitHub』をご参照ください。
AccessKeyペアの作成方法の詳細については、「AccessKeyペアの取得」をご参照ください。
バケットを作成する
バケットは OSS のグローバルネームスペースです。 バケットは、オブジェクトを格納するために使用されるコンテナです。 次のサンプルコードは、バケットの作成方法の例を示しています。
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// 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 = "yourRegion";
// Specify the temporary AccessKey pair obtained from STS.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS.
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 name of the bucket.
CreateBucketRequest createBucketRequest = new CreateBucketRequest("bucketName");
// Set the access control list (ACL) of the bucket to public-read. The default bucket ACL is private.
createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead);
// Specify the region in which 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) {
// Handle request exceptions.
if (clientException != null) {
// Handle client exceptions, such as network exceptions.
clientException.printStackTrace();
}
if (serviceException != null) {
// Handle service exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
オブジェクトのアップロード
次のサンプルコードは、ローカルファイルをOSSにアップロードする方法の例を示しています。
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// 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 = "yourRegion";
// Specify the temporary AccessKey pair obtained from STS.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS.
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);
// Construct a file upload request.
PutObjectRequest put = new PutObjectRequest("<bucketName>", "<objectName>", "<uploadFilePath>");
// When you upload the local file in asynchronous mode, you can configure the progress callback.
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) {
// Handle request exceptions.
if (clientExcepion != null) {
// Handle client exceptions, such as network exceptions.
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// Handle service exceptions.
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 download task.
// task.waitUntilFinished(); // Wait until the upload is complete.
オブジェクトのダウンロード
次のサンプルコードは、オブジェクトをローカルデバイスにダウンロードする方法の例を示しています。
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// 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 = "yourRegion";
// Specify the temporary AccessKey pair obtained from STS.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS.
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);
// Construct a request to download the object.
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 is 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) {
// You can add your own code here to process the downloaded data.
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
// If the GetObject request is successful, GetObjectResult is returned. GetObjectResult includes an instance of the input stream. You need to handle the returned input stream.
public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// Handle request exceptions.
if (clientExcepion != null) {
// Handle client exceptions, such as network exceptions.
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// Handle service exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
// Cancel the download task.
// task.cancel();
// Wait until the object is downloaded.
// task.waitUntilFinished();