OSS Android SDK kullanarak paketler oluşturun, nesneler yükleyin ve indirin.
Önkoşullar
Android SDK yüklü olmalıdır. Yükleme (Android SDK).
Örnek proje
Örnek projenin Config sınıfındaki OSS_ACCESS_KEY_ID ve OSS_ACCESS_KEY_SECRET alanları yalnızca yerel hata ayıklama ve özellik doğrulaması içindir. Üretim aşamasındaki bir mobil uygulamada uzun vadeli bir AccessKey çiftini asla sabit kodlamayın. Üretim ortamında aşağıdaki yaklaşımlardan birini kullanın:
İstemci tarafında doğrudan aktarım: Mobil uygulama, uygulama sunucunuzdan bir STS geçici kimlik bilgisi alır ve bunu bir OSSClient başlatmak için kullanır. Kurulum talimatları için bkz. Mobil uygulamalar için doğrudan veri aktarımı kurulumu.
Sunucu tarafından oluşturulan önceden imzalı URL'ler: Uygulama sunucunuz önceden imzalı URL'ler oluşturur ve bunları mobil uygulamaya iletir; uygulama standart HTTP üzerinden yükleme veya indirme yapar ve hiçbir zaman kimlik bilgisi tutmaz. Kimlik kartları, yüz görüntüleri ve ödeme kimlik bilgileri gibi gizlilik açısından hassas veriler için önerilir. Ayrıntılar için bkz. Erişimi yetkilendirme (Android SDK).
Örnek projeyi kullanmak için:
Yerel dosya yükleme, nesne indirme, kaldığı yerden devam eden yüklemeler ve geri aramalar için örnekler görmek üzere örnek dizinine göz atın.
Projeyi git kullanarak klonlayın.
Bu projeyi çalıştırmadan önce Config dosyasındaki parametreleri yapılandırın:
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;
}
STS kimlik doğrulama sunucusu URL'sini yapılandırmak için bkz. Mobil uygulama doğrudan yükleme hizmetini hızla oluşturma.
sts_local_server betiği GitHub üzerinde mevcuttur.
Bir AccessKey çifti oluşturmak için bkz. AccessKey çifti oluşturma.
Paket oluşturma
Paket, OSS içinde herhangi bir sayıda nesneyi depolayan genel olarak benzersiz bir ad alanıdır.
// 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());
}
}
});
Nesne yükleme
Yerel bir dosyayı OSS'e nesne olarak yükleyin:
// 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.
Nesne indirme
OSS'ten bir nesneyi yerel bir dosyaya indirin:
// 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();