[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
ping cos.ap-guangzhou.myqcloud.com and press Enter to perform the 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 signture 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 signture 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
<dependency><groupId>com.qcloud</groupId><artifactId>cos_api</artifactId><version>5.6.227</version></dependency>
com.qcloud.cos.*. You can use IDEs such as Eclipse or IntelliJ to import the classes required for program execution.// 1 Pass the obtained temporary credentials (tmpSecretId, tmpSecretKey, sessionToken)String tmpSecretId = "SECRETID";String tmpSecretKey = "SECRETKEY";String sessionToken = "TOKEN";BasicSessionCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);// 2 Configure the bucket region// The clientConfig includes set methods for configuring the region, https (defaulting to http), timeout, proxy, etc. For usage, refer to the source code or the Java SDK section in the FAQs.Region region = new Region("COS_REGION"); //COS_REGION parameter: Configure it to the actual region of the bucket, such as ap-beijing. For more COS region abbreviations, see https://www.tencentcloud.com/document/product/436/6224ClientConfig clientConfig = new ClientConfig(region);// 3 Generating a COS clientCOSClient cosClient = new COSClient(cred, clientConfig);
// 1 Initialize user identity information (secretId, secretKey).// To view and manage SECRETID and SECRETKEY, log in to the CAM console at https://console.tencentcloud.com/cam/capiString secretId = System.getenv("secretId");//User's SecretId. It is recommended to use sub-account keys and follow the principle of least privilege for authorization to reduce usage risks. For obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1String secretKey = System.getenv("secretKey");//User's SecretKey. It is recommended to use sub-account keys, follow the principle of least privilege for authorization to reduce usage risks. For obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// 2 Set the bucket region. For COS region abbreviations, see https://www.tencentcloud.com/document/product/436/6224// The clientConfig includes set methods for configuring region, https (defaulting to http), timeout, proxy, etc. For usage, refer to the source code or the Java SDK section in the FAQs.Region region = new Region("COS_REGION");ClientConfig clientConfig = new ClientConfig(region);// It is recommended to configure the use of the https protocol here.// Starting from version 5.6.54, https is used by defaultclientConfig.setHttpProtocol(HttpProtocol.https);// 3 Generating a cos clientCOSClient cosClient = new COSClient(cred, clientConfig);
Member Name | Setting Method | Description | Type |
region | Constructor or set method | The region where the bucket is located. For the COS region abbreviation, see the Regions and Access Domains document. | Region |
httpProtocol | set method | The protocol used for requests; HTTPS is used by default to communicate with COS. | HttpProtocol |
signExpired | set method | The validity period of the request signature: in seconds, defaults to 3600s. | long |
connectionTimeout | set method | The timeout period for connecting to the COS service, unit: milliseconds, defaults to 30000ms. | int |
socketTimeout | set method | The timeout period for the client to read data, unit: milliseconds, defaults to 30000ms. | int |
httpProxyIp | set method | Proxy Server IP | String |
httpProxyPort | set method | Port of the Proxy Server | int |
import com.qcloud.cos.COSClient;import com.qcloud.cos.ClientConfig;import com.qcloud.cos.auth.BasicCOSCredentials;import com.qcloud.cos.auth.COSCredentials;import com.qcloud.cos.exception.CosClientException;import com.qcloud.cos.exception.CosServiceException;import com.qcloud.cos.model.Bucket;import com.qcloud.cos.model.CannedAccessControlList;import com.qcloud.cos.model.CreateBucketRequest;import com.qcloud.cos.region.Region;public class BucketDemo {private static String secretId = System.getenv("SECRETID");private static String secretKey = System.getenv("SECRETKEY");private static String bucketName = System.getenv("BUCKET_NAME");private static String cosRegion = System.getenv("REGION");private static COSClient cosClient = createCli();public static void main(String[] args) {try {createBucketDemo();//createMAZBucketDemo();} catch (Exception e) {e.printStackTrace();} finally {cosClient.shutdown();}}private static COSClient createCli() {// 1 Initializing user identity information (appid, secretId, secretKey)COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// 2 Setting the region of the bucket. For abbreviations of COS regions, refer to https://www.qcloud.com/document/product/436/6224ClientConfig clientConfig = new ClientConfig(new Region(cosRegion));// 3 Generating a COS clientCOSClient cosclient = new COSClient(cred, clientConfig);return cosclient;}// Create bucketprivate static void createBucketDemo() {CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);// Set the bucket permission to PublicRead (public read, private write). Other options include private read-write, public read, private write.createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);Bucket bucket = cosClient.createBucket(createBucketRequest);System.out.println("create bucket, bucketName is " + bucket.getName());}// Create Multi-AZ bucketprivate static void createMAZBucketDemo() {CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);try {Bucket bucket = cosClient.createMAZBucket(createBucketRequest);System.out.println("create MAZ bucket, bucketName is " + bucket.getName());} catch (CosServiceException cse) {cse.printStackTrace();} catch (CosClientException cce) {cce.printStackTrace();}}}
import java.util.ArrayList;import java.util.List;import com.qcloud.cos.COSClient;import com.qcloud.cos.ClientConfig;import com.qcloud.cos.auth.BasicCOSCredentials;import com.qcloud.cos.auth.COSCredentials;import com.qcloud.cos.exception.CosClientException;import com.qcloud.cos.exception.CosServiceException;import com.qcloud.cos.model.Bucket;import com.qcloud.cos.model.ListBucketsRequest;import com.qcloud.cos.model.ListBucketsResult;import com.qcloud.cos.region.Region;public class BucketDemo {private static String secretId = System.getenv("SECRETID");private static String secretKey = System.getenv("SECRETKEY");private static String bucketName = System.getenv("BUCKET_NAME");private static String cosRegion = System.getenv("REGION");private static COSClient cosClient = createCli();public static void main(String[] args) {try {listBuckets();} catch (Exception e) {e.printStackTrace();} finally {cosClient.shutdown();}}private static COSClient createCli() {// 1 Initializing user identity information (appid, secretId, secretKey)COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// 2 Setting the region of the bucket. For abbreviations of COS regions, refer to https://www.qcloud.com/document/product/436/6224ClientConfig clientConfig = new ClientConfig(new Region(cosRegion));// 3 Generating a COS clientCOSClient cosclient = new COSClient(cred, clientConfig);return cosclient;}private static void listBuckets() {List<Bucket> buckets = cosClient.listBuckets();for (Bucket bucket : buckets) {System.out.println(bucket.getName());System.out.println(bucket.getLocation());System.out.println(bucket.getOwner());System.out.println(bucket.getType());System.out.println(bucket.getBucketType());}}}
com.qcloud.cos.transfer.\\* subpackage.examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/images/picture.jpg, the object key is images/picture.jpg. For details, see instructions in object key.import java.io.File;import com.qcloud.cos.COSClient;import com.qcloud.cos.ClientConfig;import com.qcloud.cos.auth.BasicCOSCredentials;import com.qcloud.cos.auth.COSCredentials;import com.qcloud.cos.exception.CosClientException;import com.qcloud.cos.exception.CosServiceException;import com.qcloud.cos.model.PutObjectRequest;import com.qcloud.cos.model.PutObjectResult;import com.qcloud.cos.region.Region;public class PutObjectDemo {private static String secretId = System.getenv("SECRETID");private static String secretKey = System.getenv("SECRETKEY");private static String bucketName = System.getenv("BUCKET_NAME");private static String region = System.getenv("REGION");private static COSClient cosClient = createCli();public static void main(String[] args) {try {putLocalFileDemo();} catch (Exception e) {e.printStackTrace();} finally {cosClient.shutdown();}}private static COSClient createCli() {// Initialize user identity information (secretId, secretKey)COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);// Set the region of the bucket. For COS region abbreviations, refer to https://www.qcloud.com/document/product/436/6224ClientConfig clientConfig = new ClientConfig(new Region(region));// Generate a cos clientreturn new COSClient(cred, clientConfig);}private static void putLocalFileDemo() {String key = "abc/abc.txt";String localPath = "abc.txt";PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new File(localPath));try {PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);System.out.println(putObjectResult.getRequestId());} catch (CosServiceException cse) {cse.printStackTrace();} catch (CosClientException cce) {cce.printStackTrace();}}}
import java.util.List;import com.qcloud.cos.COSClient;import com.qcloud.cos.ClientConfig;import com.qcloud.cos.auth.BasicCOSCredentials;import com.qcloud.cos.auth.COSCredentials;import com.qcloud.cos.exception.CosClientException;import com.qcloud.cos.exception.CosServiceException;import com.qcloud.cos.model.COSObjectSummary;import com.qcloud.cos.model.COSVersionSummary;import com.qcloud.cos.model.ListObjectsRequest;import com.qcloud.cos.model.ListVersionsRequest;import com.qcloud.cos.model.ObjectListing;import com.qcloud.cos.model.VersionListing;import com.qcloud.cos.region.Region;public class ListObjectsDemo {private static String secretId = System.getenv("SECRETID");private static String secretKey = System.getenv("SECRETKEY");private static String bucketName = System.getenv("BUCKET_NAME");private static String region = System.getenv("REGION");private static COSClient cosClient = createClient();public static void main(String[] args) {try {listObjectsVersions();//listObjectsDemo();//listAllObjects();} catch (Exception e) {e.printStackTrace();} finally {cosClient.shutdown();}}private static COSClient createClient() {// Initialize user identity information (secretId, secretKey)COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);// Set the region of the bucket. For COS region abbreviations, refer to https://www.qcloud.com/document/product/436/6224ClientConfig clientConfig = new ClientConfig(new Region(region));// Generate a cos clientCOSClient cosclient = new COSClient(cred, clientConfig);return cosclient;}private static void listObjectsDemo() {ListObjectsRequest listObjectsRequest = new ListObjectsRequest();// Setting the bucket namelistObjectsRequest.setBucketName(bucketName);// prefix means the key of the listed object starts with prefix.listObjectsRequest.setPrefix("");// Setting the maximum number of objects to be traversed, with a maximum number of 1000 objects supported by a listobjectlistObjectsRequest.setMaxKeys(1000);// listObjectsRequest.setDelimiter("/");ObjectListing objectListing = null;try {objectListing = cosClient.listObjects(listObjectsRequest);} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();}// common prefix indicates the path truncated by delimiter. If delimiter is set to /, common prefix indicates the path of all subdirectories.List<String> commonPrefixs = objectListing.getCommonPrefixes();// object summary represents a list of all listed objects.List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {// File path keyString key = cosObjectSummary.getKey();// File etagString etag = cosObjectSummary.getETag();// Length of the filelong fileSize = cosObjectSummary.getSize();// File storage typeString storageClasses = cosObjectSummary.getStorageClass();System.out.println("key: " + key);}}// To obtain more than the maxkey number of objects or retrieve all objects, you need to loop through listobject calls, using the next marker returned from the previous call as the marker for the next call.// Until the returned truncated is falseprivate static void listAllObjects() {ListObjectsRequest listObjectsRequest = new ListObjectsRequest();// Setting the bucket namelistObjectsRequest.setBucketName(bucketName);// prefix means the key of the listed object starts with prefix.listObjectsRequest.setPrefix("");// deliter represents the delimiter. If it is set to /, it means listing the objects in the current directory. If it is set to null, it means listing all objects.listObjectsRequest.setDelimiter("");// Setting the maximum number of objects to be traversed, with a maximum number of 1000 objects supported by a listobjectlistObjectsRequest.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 truncated by delimiter. If delimiter is set to /, common prefix indicates the path of all subdirectories.List<String> commonPrefixs = objectListing.getCommonPrefixes();// object summary represents a list of all listed objects.List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {// File path keyString key = cosObjectSummary.getKey();// File etagString etag = cosObjectSummary.getETag();// Length of the filelong fileSize = cosObjectSummary.getSize();// File storage typeString storageClasses = cosObjectSummary.getStorageClass();}String nextMarker = objectListing.getNextMarker();listObjectsRequest.setMarker(nextMarker);} while (objectListing.isTruncated());}private static void listObjectsVersions() {ListVersionsRequest listVersionsRequest = new ListVersionsRequest();listVersionsRequest.setBucketName(bucketName);listVersionsRequest.setPrefix("");VersionListing versionListing = null;do {try {versionListing = cosClient.listVersions(listVersionsRequest);} catch (CosServiceException e) {e.printStackTrace();return;} catch (CosClientException e) {e.printStackTrace();return;}List<COSVersionSummary> cosVersionSummaries = versionListing.getVersionSummaries();for (COSVersionSummary cosVersionSummary : cosVersionSummaries) {System.out.println(cosVersionSummary.getKey() + ":" + cosVersionSummary.getVersionId());}String keyMarker = versionListing.getNextKeyMarker();String versionIdMarker = versionListing.getNextVersionIdMarker();listVersionsRequest.setKeyMarker(keyMarker);listVersionsRequest.setVersionIdMarker(versionIdMarker);} while (versionListing.isTruncated());}}
import java.io.File;import java.io.IOException;import java.io.InputStream;import com.qcloud.cos.COSClient;import com.qcloud.cos.ClientConfig;import com.qcloud.cos.auth.BasicCOSCredentials;import com.qcloud.cos.auth.COSCredentials;import com.qcloud.cos.exception.CosClientException;import com.qcloud.cos.exception.CosServiceException;import com.qcloud.cos.model.COSObject;import com.qcloud.cos.model.GetObjectRequest;import com.qcloud.cos.model.ObjectMetadata;import com.qcloud.cos.region.Region;import com.qcloud.cos.utils.IOUtils;public class GetObjectDemo {private static String secretId = System.getenv("SECRETID");private static String secretKey = System.getenv("SECRETKEY");private static String bucketName = System.getenv("BUCKET_NAME");private static String region = System.getenv("REGION");private static COSClient cosClient = createClient();public static void main(String[] args) {try {getObjectToFileDemo();//getObjectInputStreamDemo();} catch (Exception e) {e.printStackTrace();} finally {cosClient.shutdown();}}private static COSClient createClient() {// Initialize user identity information (secretId, secretKey)COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);// Set the region of the bucket. For COS region abbreviations, refer to https://www.qcloud.com/document/product/436/6224ClientConfig clientConfig = new ClientConfig(new Region(region));// Generate a cos clientCOSClient cosclient = new COSClient(cred, clientConfig);return cosclient;}private static void getObjectToFileDemo() {String key = "test/my_test.json";GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);// Set the single link speed limit for download (if needed); can be ignored if not requiredgetObjectRequest.setTrafficLimit(8*1024*1024);try {File localFile = new File("my_test.json");ObjectMetadata objectMetadata = cosClient.getObject(getObjectRequest, localFile);System.out.println(objectMetadata.getContentLength());} catch (CosServiceException cse) {cse.printStackTrace();} catch (CosClientException cce) {cce.printStackTrace();}}private static void getObjectInputStreamDemo() throws IOException {String key = "test/my_test.json";GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);InputStream cosObjectInput = null;try {COSObject cosObject = cosClient.getObject(getObjectRequest);cosObjectInput = cosObject.getObjectContent();} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();}// Process the downloaded stream// This is a direct read; adjust according to actual needsbyte[] bytes = null;try {bytes = IOUtils.toByteArray(cosObjectInput);} catch (IOException e) {e.printStackTrace();} finally {// Be sure to call close() after using the streamcosObjectInput.close();}}}
import com.qcloud.cos.COSClient;import com.qcloud.cos.ClientConfig;import com.qcloud.cos.auth.BasicCOSCredentials;import com.qcloud.cos.auth.COSCredentials;import com.qcloud.cos.exception.CosClientException;import com.qcloud.cos.exception.CosServiceException;import com.qcloud.cos.region.Region;public class DelFileDemo {private static String secretId = System.getenv("SECRETID");private static String secretKey = System.getenv("SECRETKEY");private static String bucketName = System.getenv("BUCKET_NAME");private static String region = System.getenv("REGION");private static COSClient cosClient = createCli();public static void main(String[] args) {delSingleFile();if (cosClient != null) {cosClient.shutdown();}}private static COSClient createCli() {// 1 Initializing user identity information (secretId, secretKey)COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// 2 Setting the region of the bucket. For abbreviations of COS regions, refer to https://www.qcloud.com/document/product/436/6224ClientConfig clientConfig = new ClientConfig(new Region(region));// 3 Generating a COS clientCOSClient cosclient = new COSClient(cred, clientConfig);return cosclient;}// Delete a single file (without version ID, i.e., the bucket does not have versioning enabled)private static void delSingleFile() {try {String key = "aaa/bbb.txt";cosClient.deleteObject(bucketName, key);} catch (CosServiceException e) { // If there are other errors, such as parameter errors or failed authentication, a CosServiceException will be thrown.e.printStackTrace();} catch (CosClientException e) { // If there is a client error, such as failure to connect to COSe.printStackTrace();}}}
Region region = new Region("COS_REGION");ClientConfig clientConfig = new ClientConfig(region);// Set the maximum number of retries to 4clientConfig.setMaxErrorRetry = 4;
// Custom retry policypublic class OnlyIOExceptionRetryPolicy extends RetryPolicy {@Overridepublic <X extends CosServiceRequest> boolean shouldRetry(CosHttpRequest<X> request,HttpResponse response,Exception exception,int retryIndex) {// If it is a client-side IOException, retry; otherwise, do not retryif (exception.getCause() instanceof IOException) {return true;}return false;}}Region region = new Region("COS_REGION");ClientConfig clientConfig = new ClientConfig(region);RetryPolicy myRetryPolicy = new OnlyIOExceptionRetryPolicy();// Set the custom retry policyclientConfig.setRetryPolicy(myRetryPolicy);
Apakah halaman ini membantu?
Anda juga dapat Menghubungi Penjualan atau Mengirimkan Tiket untuk meminta bantuan.
masukan