tencent cloud

Cloud Object Storage

Generating Pre-Signed URLs

Download
Modo Foco
Tamanho da Fonte
Última atualização: 2026-05-15 15:26:30

Introduction

This document provides example code and a description for generating pre-signed object URLs using the COS Android SDK.

Must-Knows

Buckets created after January 1, 2024 do not support previewing files in a browser using the default domain name. We recommend that you configure a custom domain name. For details, see Switching to a Custom Domain Name for a Bucket.
We recommend that you use temporary keys to generate pre-signed URLs. This approach, which leverages temporary authorization, further enhances the security of requests such as pre-signed uploads and downloads. When applying for temporary keys, follow the principle of least privilege to prevent the exposure of resources beyond the target bucket or object.
If you must use a permanent key to generate a pre-signed URL, we recommend that you limit the key's permissions to upload or download operations only to mitigate risks.
When a file is uploaded with a pre-signed URL, the maximum supported file size is 5 GB.
By default, the Host Header is signed when a pre-signed URL is generated. You can choose not to sign the Host Header, but this may cause request failures or security vulnerabilities.
For instructions on uploading with a pre-signed URL, see Pre-signed Authorization Upload. For instructions on downloading with a pre-signed URL, see Pre-signed Authorization Download.

Related Examples

Feature Name
Description
Example code
Generate presigned URL
COS (Cloud Object Storage) supports using pre-signed URLs to upload and download objects. The principle is to embed the signature into the URL to generate a signed link.

Preliminary Preparation

Creating a CosXmlService

Before calling a COS API, you must first create a CosXmlService instance. For detailed code, see Creating CosXmlService.

Use Cases

Generating a Pre-Signed Upload URL and Uploading an Object

try {
// Bucket name
String bucket = "examplebucket-1250000000";
// The location identifier of the object in the bucket. The object key (Key) is the unique identifier of the object within the bucket. For details, see [Object Key](https://www.tencentcloud.com/document/product/436/13324?from_cn_redirect=1#.E5.AF.B9.E8.B1.A1.E9.94.AE).
// Note: You do not need to encode the cosPath.
String cosPath = "exampleobject";
// Request HTTP method
String method = "PUT";
// Local file path final String localPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/wechat.png";
PresignedUrlRequest presignedUrlRequest = new PresignedUrlRequest(bucket
, cosPath) {
@Override
public RequestBodySerializer getRequestBody()
throws CosXmlClientException {
// Used to calculate the signature URL for requests such as put that require a request body.
return RequestBodySerializer.file(null, new File(localPath));
}
};
presignedUrlRequest.setRequestMethod(method);
// Sets the signature validity period to 60 seconds. Note that this is the signature validity period. You must ensure the key validity period yourself.
presignedUrlRequest.setSignKeyTime(60);
// Do not sign a specific header.
// presignedUrlRequest.addNoSignHeader("XXX");
// presignedUrlRequest.addNoSignHeader("Content-Length"); // presignedUrlRequest.addNoSignHeader("Content-Type");
// Obtain the pre-signed upload URL.
String urlWithSign = cosXmlService.getPresignedURL(presignedUrlRequest);
// Start upload.
new Thread(new Runnable() { @Override public void run() { uploadFile(urlWithSign, localPath); } }).start();
} catch (CosXmlClientException e) {
e.printStackTrace();
}
Upload files using HttpURLConnection.
public void uploadFile(String targetUrl, String filePath) { int retryCount = 0; boolean success = false; while (!success && retryCount < 3) { HttpURLConnection connection = null; DataOutputStream outputStream = null; FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(filePath); URL url = new URL(targetUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("PUT");
// Set the specific Content-Type for the network request, for example, image/jpeg.
connection.setRequestProperty("Content-Type", "application/octet-stream"); outputStream = new DataOutputStream(connection.getOutputStream()); int bytesRead; byte[] buffer = new byte[8192]; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { if (connection.getResponseCode() >= 500) { retryCount++; continue; } else { throw new RuntimeException("Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } success = true; } catch (Exception e) { retryCount++; } finally { try { if (outputStream != null) outputStream.close(); if (fileInputStream != null) fileInputStream.close(); } catch (Exception ignored) { } if (connection != null) connection.disconnect(); } } if (!success) { throw new RuntimeException("Failed to upload file after 3 attempts"); } }

Generating a Pre-Signed Download URL and Downloading an Object

try {
// Bucket name
String bucket = "examplebucket-1250000000";
// The location identifier of the object in the bucket. The object key (Key) is the unique identifier of the object within the bucket. For details, see [Object Key](https://www.tencentcloud.com/document/product/436/13324?from_cn_redirect=1#.E5.AF.B9.E8.B1.A1.E9.94.AE).
// Note: You do not need to encode the cosPath.
String cosPath = "exampleobject";
// Request HTTP method.
String method = "GET";
PresignedUrlRequest presignedUrlRequest = new PresignedUrlRequest(bucket
, cosPath);
presignedUrlRequest.setRequestMethod(method);

// Sets the signature validity period to 60 seconds. Note that this is the signature validity period. You must ensure the key validity period yourself.
presignedUrlRequest.setSignKeyTime(60);
// Do not sign a specific header.
// presignedUrlRequest.addNoSignHeader("XXX");
// presignedUrlRequest.addNoSignHeader("Content-Length"); // presignedUrlRequest.addNoSignHeader("Content-Type");

// Obtain the pre-signed download URL.
String urlWithSign = cosXmlService.getPresignedURL(presignedUrlRequest);
// Start download.
new Thread(new Runnable() { @Override public void run() { String localPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/wechat.png"; downloadFile(urlWithSign, localPath); } }).start();
} catch (CosXmlClientException e) {
e.printStackTrace();
}
Download files using HttpURLConnection.
public void downloadFile(String fileUrl, String localPath) {
int retryCount = 0;
boolean success = false;
while (!success && retryCount < 3) {
HttpURLConnection connection = null;
InputStream input = null;
FileOutputStream output = null;
try {
URL url = new URL(fileUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
if (connection.getResponseCode() >= 500) {
retryCount++;
continue;
} else {
throw new RuntimeException("Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage());
}
}
input = connection.getInputStream();
output = new FileOutputStream(localPath);
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
success = true;
} catch (Exception e) {
retryCount++;
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (Exception ignored) {
}
if (connection != null)
connection.disconnect();
}
}
if (!success) {
throw new RuntimeException("Failed to download file after 3 attempts");
}
}

SDK API Reference

For detailed parameters and method descriptions of all SDK interfaces, see SDK API Reference.

Ajuda e Suporte

Esta página foi útil?

comentários