android 使用sts s3上傳
服務端生成sts給的AWS憑證是動態的,每1小時更新一次。
dependencies { def aws_version = "2.16.+" implementation "com.amazonaws:aws-android-sdk-s3:$aws_version" implementation ("com.amazonaws:aws-android-sdk-mobile-client:$aws_version") { transitive = true } }
public void downloadFileByKey(String key) throws JSONException { JSONObject jsonConfig = new JSONObject(); JSONObject s3TransferUtility = new JSONObject(); jsonConfig.putOpt("S3TransferUtility", s3TransferUtility); s3TransferUtility.put("Region", "服務端請求來的region"); s3TransferUtility.put("Bucket", "服務端請求來bucket"); AWSSessionCredentials credentials = new AWSSessionCredentials() { @Override public String getSessionToken() { return "服務端請求過來的SessionToken"; } @Override public String getAWSAccessKeyId() { return "服務端請求來的AccessKey"; } @Override public String getAWSSecretKey() { return "服務端請求來的SecretKey"; } }; AWSConfiguration configuration = new AWSConfiguration(jsonConfig); TransferUtility utility = TransferUtility.builder() .context(this) .s3Client(new AmazonS3Client(credentials)) .awsConfiguration(configuration) .build(); File file = new File(Environment.getExternalStorageDirectory().getPath() + "/test44.png"); TransferObserver observer = utility.download(key, file); observer.setTransferListener(new TransferListener() { @Override public void onStateChanged(int i, TransferState transferState) { if (transferState == TransferState.COMPLETED) { //下載完成了 } } @Override public void onProgressChanged(int i, long l, long l1) { } @Override public void onError(int i, Exception e) { //下載出錯 } }); }
以上是下載文件,上傳文件類似:
TransferObserver observer = utility.upload(key, file);