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. |
try {// Bucket nameString 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 methodString method = "PUT";// Local file path final String localPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/wechat.png";PresignedUrlRequest presignedUrlRequest = new PresignedUrlRequest(bucket, cosPath) {@Overridepublic 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();}
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"); } }
try {// Bucket nameString 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();}
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");}}
Esta página foi útil?
Você também pode entrar em contato com a Equipe de vendas ou Enviar um tíquete em caso de ajuda.
comentários