build.gradle file (usually in the root directory):repositories {google()// Add the following linemavenCentral()}
build.gradle file (usually under the App module).dependencies {...// Add the following lineimplementation 'com.qcloud.cos:cos-android:5.9.+'}
build.gradle file (usually under the App module).dependencies {...// Add the following lineimplementation 'com.qcloud.cos:cos-android-lite:5.9.+'}
build.gradle file (usually under the App module):cos-android todependencies {...// Change toimplementation 'com.qcloud.cos:cos-android-nobeacon:x.x.x'//For lite version, change toimplementation 'com.qcloud.cos:cos-android-lite-nobeacon:x.x.x'}
dependencies {...implementation ('com.qcloud.cos:cos-android:x.x.x'){// Add the following lineexclude group: 'com.tencent.qcloud', module: 'beacon-android-release'}}
JAR or AAR packages as described below. Please choose the ones you want to integrate.libs folder and add dependencies to the app-level build.gradle file (usually under the App module):dependencies {...// Add the following lineimplementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])}
AndroidManifest.xml under the app module:<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
AndroidManifest.xml under the app module:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
BasicLifecycleCredentialProvider subclass to request a temporary key and return the result.public static class MySessionCredentialProviderextends BasicLifecycleCredentialProvider {@Overrideprotected QCloudLifecycleCredentials fetchNewCredentials()throws QCloudClientException {// First, obtain the response containing the key from your temporary key server// Then, parse the response to obtain the temporary keyString tmpSecretId = "SECRETID"; // SecretId of the temporary keyString tmpSecretKey = "SECRETKEY"; // SecretKey of the temporary keyString sessionToken = "SESSIONTOKEN"; // Token of the temporary keylong expiredTime = 1556183496L;// End timestamp (in seconds) of the effective period of the temporary key// To avoid request expiration caused by the large discrepancy between the phone’s local time and the standard time, we recommend that the time returning to the server be used as the signature start time.// Time returning to the server as the signature start timelong startTime = 1556182000L; // Start timestamp (in seconds) of the effective period of the temporary key// Finally, return the temporary key objectreturn new SessionQCloudCredentials(tmpSecretId, tmpSecretKey,sessionToken, startTime, expiredTime);}}
MySessionCredentialProvider as the class name example to initialize an instance to provide a key for the SDK.QCloudCredentialProvider myCredentialProvider = new MySessionCredentialProvider();
String secretId = "SECRETID"; // SecretId of the permanent keyString secretKey = "SECRETKEY"; // SecretKey of the permanent key// keyDuration is the effective duration (in seconds) of the key in your requestQCloudCredentialProvider myCredentialProvider =new ShortTimeCredentialProvider(secretId, secretKey, 300);
QCloudSelfSigner to get the server-side signature and add it to the request authorization.QCloudSelfSigner myQCloudSelfSigner = new QCloudSelfSigner() {/*** Sign the request** @param request The request to be signed* @throws QCloudClientException Client exception*/@Overridepublic void sign(QCloudHttpRequest request) throws QCloudClientException {// 1. Pass the request parameters to the server to calculate the signatureString auth = "get auth from server";// 2. Add the signature to the requestrequest.addHeader(HttpConstants.Header.AUTHORIZATION, auth);}});
myCredentialProvider instance that provides the key or the server-side signed and authorized instance myQCloudSelfSigner to initialize a CosXmlService instance.CosXmlService provides all APIs for accessing COS. We recommend you use it as an application singleton.// Bucket region abbreviation. For example, "ap-guangzhou" is the abbreviation of the Guangzhou regionString region = "COS_REGION";// Create a `CosXmlServiceConfig` object and modify the default configuration parameters as neededCosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder().setRegion(region).isHttps(true) // Use the HTTPS request. HTTP is used by default.builder();// Initialize the COS service to obtain the instanceCosXmlService cosXmlService = new CosXmlService(context,serviceConfig, myCredentialProvider);// Initialize the COS service via the server-side signature authorization to get the instanceCosXmlService cosXmlService = new CosXmlService(context,serviceConfig, myQCloudSelfSigner);
// Initialize TransferConfig. The default configuration is used here. To customize the configuration, see the SDK API documentation.TransferConfig transferConfig = new TransferConfig.Builder().build();// Initialize TransferManager.TransferManager transferManager = new TransferManager(cosXmlService,transferConfig);// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.String bucket = "examplebucket-1250000000";String cosPath = "exampleobject"; // Location identifier of the object in the bucket, i.e., the object keyString srcPath = new File(context.getCacheDir(), "exampleobject").toString(); // Absolute path of the local file// If there is an uploadId for the initialized multipart upload, assign the value of uploadId here to resume the upload. Otherwise, assign nullString uploadId = null;// Upload the fileCOSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath,srcPath, uploadId);// Set the callback for initializing multipart upload (supported starting from v5.9.7)cosxmlUploadTask.setInitMultipleUploadListener(new InitMultipleUploadListener() {@Overridepublic void onSuccess(InitiateMultipartUpload initiateMultipartUpload) {//The uploadId required for the subsequent checkpoint restartsString uploadId = initiateMultipartUpload.uploadId;}});// Set the upload progress callbackcosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {@Overridepublic void onProgress(long complete, long target) {// todo Do something to update progress...}});// Set the response callbackcosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {@Overridepublic void onSuccess(CosXmlRequest request, CosXmlResult result) {COSXMLUploadTask.COSXMLUploadTaskResult uploadResult =(COSXMLUploadTask.COSXMLUploadTaskResult) result;}// If you use the Kotlin language to call this, please note that the exception in the callback method is nullable; otherwise, the onFail method will not be called back, that is:// clientException is of type CosXmlClientException? and serviceException is of type CosXmlServiceException?@Overridepublic void onFail(CosXmlRequest request,@Nullable CosXmlClientException clientException,@Nullable CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else{serviceException.printStackTrace();}}});// Set the job status callback to view the job progresscosxmlUploadTask.setTransferStateListener(new TransferStateListener() {@Overridepublic void onStateChanged(TransferState state) {// todo notify transfer state}});
// The advanced download API supports checkpoint restart. Therefore, a HEAD request will be sent before the download to obtain the file information.// If you are using a temporary key or accessing with a sub-account, ensure that your permission list includes HeadObject.// Initialize TransferConfig. The default configuration is used here. To customize the configuration, see the SDK API documentation.TransferConfig transferConfig = new TransferConfig.Builder().build();// Initialize TransferManagerTransferManager transferManager = new TransferManager(cosXmlService,transferConfig);// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.String bucket = "examplebucket-1250000000";String cosPath = "exampleobject"; // Location identifier of the object in the bucket, i.e., the object key// Path of the local directoryString savePathDir = context.getExternalCacheDir().toString();// File name saved locally. If not specified (null), it will be the same as the COS file nameString savedFileName = "exampleobject";Context applicationContext = context.getApplicationContext(); // application// contextCOSXMLDownloadTask cosxmlDownloadTask =transferManager.download(applicationContext,bucket, cosPath, savePathDir, savedFileName);// Set the download progress callbackcosxmlDownloadTask.setCosXmlProgressListener(new CosXmlProgressListener() {@Overridepublic void onProgress(long complete, long target) {// todo Do something to update progress...}});// Set the response callbackcosxmlDownloadTask.setCosXmlResultListener(new CosXmlResultListener() {@Overridepublic void onSuccess(CosXmlRequest request, CosXmlResult result) {COSXMLDownloadTask.COSXMLDownloadTaskResult downloadTaskResult =(COSXMLDownloadTask.COSXMLDownloadTaskResult) result;}// If you use the Kotlin language to call this, please note that the exception in the callback method is nullable; otherwise, the onFail method will not be called back, that is:// clientException is of type CosXmlClientException? and serviceException is of type CosXmlServiceException?@Overridepublic void onFail(CosXmlRequest request,@Nullable CosXmlClientException clientException,@Nullable CosXmlServiceException serviceException) {if (clientException != null) {clientException.printStackTrace();} else{serviceException.printStackTrace();}}});// Set the job status callback to view the job progresscosxmlDownloadTask.setTransferStateListener(new TransferStateListener() {@Overridepublic void onStateChanged(TransferState state) {// todo notify transfer state}});
HeadObject.Feedback