<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
ping cos.ap-guangzhou.myqcloud.com
并回车进行测试。[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
com.qcloud.cos.*
,您可以通过 Eclipse 或者 Intellij 等 IDE 工具,导入程序运行所需要的类。// 1 传入获取到的临时密钥 (tmpSecretId, tmpSecretKey, sessionToken)String tmpSecretId = "SECRETID";String tmpSecretKey = "SECRETKEY";String sessionToken = "TOKEN";BasicSessionCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);// 2 设置 bucket 的地域// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分Region region = new Region("COS_REGION"); //COS_REGION 参数:配置成存储桶 bucket 的实际地域,例如 ap-beijing,更多 COS 地域的简称请参见 https://www.tencentcloud.com/document/product/436/6224ClientConfig clientConfig = new ClientConfig(region);// 3 生成 cos 客户端COSClient cosClient = new COSClient(cred, clientConfig);
// 1 初始化用户身份信息(secretId, secretKey)。// SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.tencentcloud.com/cam/capi 进行查看和管理String secretId = System.getenv("secretId");//用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1String secretKey = System.getenv("secretKey");//用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// 2 设置 bucket 的地域, COS 地域的简称请参见 https://www.tencentcloud.com/document/product/436/6224// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。Region region = new Region("COS_REGION");ClientConfig clientConfig = new ClientConfig(region);// 这里建议设置使用 https 协议// 从 5.6.54 版本开始,默认使用了 httpsclientConfig.setHttpProtocol(HttpProtocol.https);// 3 生成 cos 客户端。COSClient cosClient = new COSClient(cred, clientConfig);
成员名 | 设置方法 | 描述 | 类型 |
region | 构造函数或 set 方法 | Region | |
httpProtocol | set 方法 | 请求所使用的协议,默认使用 HTTPS 协议与 COS 交互 | HttpProtocol |
signExpired | set 方法 | 请求签名的有效时间,单位:秒,默认为3600s | long |
connectionTimeout | set 方法 | 连接 COS 服务的超时时间,单位:毫秒,默认为30000ms | int |
socketTimeout | set 方法 | 客户端读取数据的超时时间,单位:毫秒,默认为30000ms | int |
httpProxyIp | set 方法 | 代理服务器的 IP | String |
httpProxyPort | set 方法 | 代理服务器的端口 | int |
String bucket = "examplebucket-1250000000"; //存储桶名称,格式:BucketName-APPIDCreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);// 设置 bucket 的权限为 Private(私有读写)、其他可选有 PublicRead(公有读私有写)、PublicReadWrite(公有读写)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.\\*
子包下。examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/images/picture.jpg
中,对象键为 images/picture.jpg,详情请参见 对象键 的说明。// 指定要上传的文件File localFile = new File(localFilePath);// 指定文件将要存放的存储桶String bucketName = "examplebucket-1250000000";// 指定文件上传到 COS 上的路径,即对象键。例如对象键为 folder/picture.jpg,则表示将文件 picture.jpg 上传到 folder 路径下String key = "exampleobject";PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
// Bucket 的命名格式为 BucketName-APPID ,此处填写的存储桶名称必须为此格式String bucketName = "examplebucket-1250000000";ListObjectsRequest listObjectsRequest = new ListObjectsRequest();// 设置 bucket 名称listObjectsRequest.setBucketName(bucketName);// prefix 表示列出的 object 的 key 以 prefix 开始listObjectsRequest.setPrefix("images/");// deliter 表示分隔符, 设置为/表示列出当前目录下的 object, 设置为空表示列出所有的 objectlistObjectsRequest.setDelimiter("/");// 设置最大遍历出多少个对象, 一次 listobject 最大支持1000listObjectsRequest.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 表示表示被 delimiter 截断的路径, 如 delimter 设置为/, common prefix 则表示所有子目录的路径List<String> commonPrefixs = objectListing.getCommonPrefixes();// object summary 表示所有列出的 object 列表List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {// 文件的路径 keyString key = cosObjectSummary.getKey();// 文件的 etagString etag = cosObjectSummary.getETag();// 文件的长度long fileSize = cosObjectSummary.getSize();// 文件的存储类型String storageClasses = cosObjectSummary.getStorageClass();}String nextMarker = objectListing.getNextMarker();listObjectsRequest.setMarker(nextMarker);} while (objectListing.isTruncated());
// Bucket 的命名格式为 BucketName-APPID ,此处填写的存储桶名称必须为此格式String bucketName = "examplebucket-1250000000";// 指定文件在 COS 上的路径,即对象键。例如对象键为 folder/picture.jpg,则表示下载的文件 picture.jpg 在 folder 路径下String key = "exampleobject";// 方法1 获取下载输入流GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);COSObject cosObject = cosClient.getObject(getObjectRequest);COSObjectInputStream cosObjectInput = cosObject.getObjectContent();// 下载对象的 CRC64String crc64Ecma = cosObject.getObjectMetadata().getCrc64Ecma();// 关闭输入流cosObjectInput.close();// 方法2 下载文件到本地的路径,例如 D 盘的某个目录String outputFilePath = "exampleobject";File downFile = new File(outputFilePath);getObjectRequest = new GetObjectRequest(bucketName, key);ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
// Bucket 的命名格式为 BucketName-APPID ,此处填写的存储桶名称必须为此格式String bucketName = "examplebucket-1250000000";// 指定被删除的文件在 COS 上的路径,即对象键。例如对象键为 folder/picture.jpg,则表示删除位于 folder 路径下的文件 picture.jpgString key = "exampleobject";cosClient.deleteObject(bucketName, key);
Region region = new Region("COS_REGION");ClientConfig clientConfig = new ClientConfig(region);// 设置最大重试次数为 4 次clientConfig.setMaxErrorRetry = 4;
// 自定义重试策略public class OnlyIOExceptionRetryPolicy extends RetryPolicy {@Overridepublic <X extends CosServiceRequest> boolean shouldRetry(CosHttpRequest<X> request,HttpResponse response,Exception exception,int retryIndex) {// 如果是客户端的 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();// 设置自定义的重试策略clientConfig.setRetryPolicy(myRetryPolicy);
// 关闭客户端(关闭后台线程)cosClient.shutdown();
本页内容是否解决了您的问题?