<dependency><groupId>com.qcloud</groupId><artifactId>cos_api</artifactId><version>5.6.133</version></dependency>
[root@VM_centos /data/home/]# ping cos.ap-guangzhou.myqcloud.comPING cos.ap-guangzhou.myqcloud.com (9.*.*.*) xx(xx) bytes of data.64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=1 ttl=xx time=0.xxx ms64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=2 ttl=xx time=0.xxx ms64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=3 ttl=xx time=0.xxx ms64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=4 ttl=xx time=0.xxx ms64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=5 ttl=xx time=0.xxx ms64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=6 ttl=xx time=0.xxx ms64 bytes from 9.*.*.* (9.*.*.*): icmp_seq=7 ttl=xx time=0.xxx ms^C--- cos.ap-guangzhou.myqcloud.com ping statistics ---x packets transmitted, x received, 0% packet loss, time xxxmsrtt min/avg/max/mdev = 0.xxx/0.xxx/0.xxx/0.xxx ms
cmd
) > OK (or press Enter), type the ping cos.ap-guangzhou.myqcloud.com
command, and press Enter to test.[root@VM_centos /data/home/]# curl http://cos.ap-guangzhou.myqcloud.com -v* About to connect() to cos.ap-guangzhou.myqcloud.com port 80 (#0)* Trying 9.*.*.*...* Connected to cos.ap-guangzhou.myqcloud.com (9.*.*.*) port 80 (#0)> GET / HTTP/1.1> User-Agent: curl/*.*.0> Host: cos.ap-guangzhou.myqcloud.com> Accept: */*>< HTTP/1.1 403 Forbidden< Content-Type: application/xml< Content-Length: XXX< Connection: keep-alive< Date: XXX XXX GMT< Server: tencent-cos< x-cos-request-id: NWE2MWQ5MjZfMTBhYzM1MGFfMTA5ODVfMTVj****<<?xml version='1.0' encoding='utf-8' ?><Error><Code>AccessDenied</Code><Message>Check auth failure because signature empty.</Message><ServerTime>XXX XXX</ServerTime><Resource>cos.ap-guangzhou.myqcloud.com/</Resource><RequestId>NWE2MWQ5MjZfMTBhYzM1MGFfMTA5ODVfMTVj****==</RequestId></Error>* Connection #0 to host cos.ap-guangzhou.myqcloud.com left intact
[root@VM_centos /data/home/]# curl https://cos.ap-guangzhou.myqcloud.com -vk* About to connect() to cos.ap-guangzhou.myqcloud.com port 443 (#0)* Trying 9.*.*.*...* Connected to cos.ap-guangzhou.myqcloud.com (9.*.*.*) port 443 (#0)* Initializing NSS with certpath: XXXX* skipping SSL peer certificate verification* SSL connection using ******* Server certificate:* subject: CN=*.*.*.* start date: XXX XXX GMT* expire date: XXX XXX GMT* common name: *.cos.ap-guangzhou.myqcloud.com* issuer: XXX> GET / HTTP/1.1> User-Agent: curl/*.*.0> Host: cos.ap-guangzhou.myqcloud.com> Accept: */*>< HTTP/1.1 403 Forbidden< Content-Type: application/xml< Content-Length: XXX< Connection: keep-alive< Date: XXX XXX GMT< Server: tencent-cos< x-cos-request-id: NWE2MWQ5MjZfMTBhYzM1MGFfMTA5ODVfMTVj****<<?xml version='1.0' encoding='utf-8' ?><Error><Code>AccessDenied</Code><Message>Check auth failure because signature empty.</Message><ServerTime>XXX XXX</ServerTime><Resource>cos.ap-guangzhou.myqcloud.com/</Resource><RequestId>NWE2MWQ5MjZfMTBhYzM1MGFfMTA5ODVfMTVj****</RequestId></Error>* Connection #0 to host cos.ap-guangzhou.myqcloud.com left intact
com.qcloud.cos.*
. You can import the classes required for running your program through your IDE, such as Eclipse and IntelliJ.// 1. Pass in the obtained temporary key (tmpSecretId, tmpSecretKey, sessionToken).String tmpSecretId = "SECRETID";String tmpSecretKey = "SECRETKEY";String sessionToken = "TOKEN";BasicSessionCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);// 2. Set the bucket region.// `clientConfig` contains the set methods to set region, HTTPS (HTTP by default), timeout, and proxy. For detailed usage, see the source code or the FAQs about the SDK for Java.Region region = new Region("COS_REGION"); //COS_REGION parameter, which needs to be set to the actual region of the bucket, for example, ap-beijing. For the abbreviations for more COS regions, visit https://www.tencentcloud.com/document/product/436/6224.ClientConfig clientConfig = new ClientConfig(region);// 3. Generate a COS clientCOSClient cosClient = new COSClient(cred, clientConfig);
APPId
, SecretId
, and SecretKey
on the Manage API Key page of the CAM console. An example is shown below:// 1. Initialize the user credentials (secretId, secretKey).// Log in to the [CAM console](https://console.tencentcloud.com/cam/capi) to view and manage the `SecretId` and `SecretKey` of your project.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// 2. Set the bucket region. For the abbreviations for COS regions, please visit https://www.tencentcloud.com/document/product/436/6224.// `clientConfig` contains the set methods to set region, HTTPS (HTTP by default), timeout, and proxy. For detailed usage, see the source code or the FAQs about the SDK for Java.Region region = new Region("COS_REGION");ClientConfig clientConfig = new ClientConfig(region);// The HTTPS protocol is recommended.// Starting from 5.6.54, HTTPS is used by default.clientConfig.setHttpProtocol(HttpProtocol.https);// 3. Generate a COS client.COSClient cosClient = new COSClient(cred, clientConfig);
Member Name | Setting Method | Description | Type |
region | Constructor or set method | Region | |
httpProtocol | Set method | The protocol used by the request. By default, HTTPS is used to interact with COS. | HttpProtocol |
signExpired | Set method | Validity period (in seconds) of the request signature. Default: 3600s | long |
connectionTimeout | Set method | Timeout duration in milliseconds for connection with COS. Default value: 30000 ms | int |
socketTimeout | Set method | Timeout duration in milliseconds for the client to read data. Default value: 30000 ms | int |
httpProxyIp | Set method | Proxy server IP | String |
httpProxyPort | Set method | Proxy server port | int |
String bucket = "examplebucket-1250000000"; // Bucket, formatted as BucketName-APPIDCreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);// Set the bucket permission to "Private" (private read and write). Other valid values are "PublicRead" (public read/private write) and "PublicReadWrite" (public read and write).createBucketRequest.setCannedAcl(CannedAccessControlList.Private);try{Bucket bucketResult = cosClient.createBucket(createBucketRequest);} catch (CosServiceException serverException) {serverException.printStackTrace();} catch (CosClientException clientException) {clientException.printStackTrace();}
List<Bucket> buckets = cosClient.listBuckets();for (Bucket bucketElement : buckets) {String bucketName = bucketElement.getName();String bucketLocation = bucketElement.getLocation();}
com.qcloud.cos.transfer.\\*
sub-package.examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/images/picture.jpg
, the object key is images/picture.jpg
. For more information, see Object Key.// Specify the file to be uploaded.File localFile = new File(localFilePath);// Specify a bucket to store the file.String bucketName = "examplebucket-1250000000";// Specify the COS path (i.e. the object key) to upload the file. For example, if the object key is "folder/picture.jpg", the file "picture.jpg" will be uploaded to the "folder" directory.String key = "exampleobject";PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";ListObjectsRequest listObjectsRequest = new ListObjectsRequest();// Set the bucket namelistObjectsRequest.setBucketName(bucketName);// Prefix indicates that the object keys to be listed begin with this prefixlistObjectsRequest.setPrefix("images/");// Delimiter is a separator. Set it to "/" to list objects in the current directory; set it to null to list all objects.listObjectsRequest.setDelimiter("/");// Set the maximum number of objects to be traversed, which can be up to 1,000 in one listobject operationlistObjectsRequest.setMaxKeys(1000);ObjectListing objectListing = null;do {try{objectListing = cosClient.listObjects(listObjectsRequest);} catch (CosServiceException e) {e.printStackTrace();return;} catch (CosClientException e) {e.printStackTrace();return;}// `common prefix` indicates the path that ends with the `delimiter`. If the `delimiter` is set to "/", the `common prefix` indicates the paths of all subdirectories.List<String> commonPrefixs = objectListing.getCommonPrefixes();// The object summary shows all listed objects.List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {// File path keyString key = cosObjectSummary.getKey();// `ETag` of the fileString etag = cosObjectSummary.getETag();// File sizelong fileSize = cosObjectSummary.getSize();// File storage classString storageClasses = cosObjectSummary.getStorageClass();}String nextMarker = objectListing.getNextMarker();listObjectsRequest.setMarker(nextMarker);} while (objectListing.isTruncated());
// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Specify the COS path (i.e. the object key) of the file to download. For example, if the object key is "folder/picture.jpg", the file "picture.jpg" in the "folder" directory will be downloaded.String key = "exampleobject";// Method 1. Get the input stream of the downloaded file.GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);COSObject cosObject = cosClient.getObject(getObjectRequest);COSObjectInputStream cosObjectInput = cosObject.getObjectContent();// Download the CRC64 value of the object.String crc64Ecma = cosObject.getObjectMetadata().getCrc64Ecma();// Close the input stream.cosObjectInput.close();// Method 2: Download the file to a local directory, e.g. a directory in D drive.String outputFilePath = "exampleobject";File downFile = new File(outputFilePath);getObjectRequest = new GetObjectRequest(bucketName, key);ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Specify the COS path (i.e. the object key) of the file to delete. For example, if the object key is "folder/picture.jpg", the "picture.jpg" file in the "folder" directory will be deleted.String key = "exampleobject";cosClient.deleteObject(bucketName, key);
3
. You can set it using clientConfig.setMaxErrorRetry
.
If set to 0
, no retry will be performed on all types of request errors.Region region = new Region("COS_REGION");ClientConfig clientConfig = new ClientConfig(region);// Set the maximum number of retries to 4.clientConfig.setMaxErrorRetry = 4;
// Customize a retry policy.public class OnlyIOExceptionRetryPolicy extends RetryPolicy {@Overridepublic <X extends CosServiceRequest> boolean shouldRetry(CosHttpRequest<X> request,HttpResponse response,Exception exception,int retryIndex) {// Retry only for client-side IOException.if (exception.getCause() instanceof IOException) {return true;}return false;}}Region region = new Region("COS_REGION");ClientConfig clientConfig = new ClientConfig(region);RetryPolicy myRetryPolicy = new OnlyIOExceptionRetryPolicy();// Configure the custom retry policy.clientConfig.setRetryPolicy(myRetryPolicy);
// Close the client (release server threads).cosClient.shutdown();
Was this page helpful?