简介
本文档提供关于生成对象预签名链接的示例代码。
说明
建议用户使用临时密钥生成预签名,通过临时授权的方式进一步提高预签名上传、下载等请求的安全性。申请临时密钥时,请遵循 最小权限指引原则,防止泄露目标存储桶或对象之外的资源。
如果您一定要使用永久密钥来生成预签名,建议永久密钥的权限范围仅限于上传或下载操作,以规避风险。
SDK API 参考
生成对象预签名链接
示例代码一:生成预签名上传链接
try {//存储桶名称String bucket = "examplebucket-1250000000";// 对象在存储桶中的位置标识符,对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent.com/document/product/436/13324#.E5.AF.B9.E8.B1.A1.E9.94.AE)// 注意:用户无需对 cosPath 进行编码操作String cosPath = "exampleobject";//请求 HTTP 方法String method = "PUT";PresignedUrlRequest presignedUrlRequest = new PresignedUrlRequest(bucket, cosPath) {@Overridepublic RequestBodySerializer getRequestBody()throws CosXmlClientException {//用于计算 put 等需要带上 body 的请求的签名 URLreturn RequestBodySerializer.string("text/plain","this is test");}};presignedUrlRequest.setRequestMethod(method);// 设置签名有效期为 60s,注意这里是签名有效期,您需要自行保证密钥有效期presignedUrlRequest.setSignKeyTime(60);// 设置不签名 HostpresignedUrlRequest.addNoSignHeader("Host");String urlWithSign = cosXmlService.getPresignedURL(presignedUrlRequest);} catch (CosXmlClientException e) {e.printStackTrace();}
说明
示例代码二:生成预签名下载链接
try {//存储桶名称String bucket = "examplebucket-1250000000";// 对象在存储桶中的位置标识符,对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent.com/document/product/436/13324#.E5.AF.B9.E8.B1.A1.E9.94.AE)// 注意:用户无需对 cosPath 进行编码操作String cosPath = "exampleobject";//请求 HTTP 方法.String method = "GET";PresignedUrlRequest presignedUrlRequest = new PresignedUrlRequest(bucket, cosPath);presignedUrlRequest.setRequestMethod(method);// 设置签名有效期为 60s,注意这里是签名有效期,您需要自行保证密钥有效期presignedUrlRequest.setSignKeyTime(60);// 设置不签名 HostpresignedUrlRequest.addNoSignHeader("Host");String urlWithSign = cosXmlService.getPresignedURL(presignedUrlRequest);} catch (CosXmlClientException e) {e.printStackTrace();}
说明