Path: blob/master/code_examples/java_examples/S3Examples/GeneratePresignedURL.java
4084 views
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.1// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE.)23import java.io.IOException;4import java.net.URL;56import com.amazonaws.AmazonServiceException;7import com.amazonaws.HttpMethod;8import com.amazonaws.SdkClientException;9import com.amazonaws.auth.profile.ProfileCredentialsProvider;10import com.amazonaws.services.s3.AmazonS3;11import com.amazonaws.services.s3.AmazonS3ClientBuilder;12import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;1314public class GeneratePresignedURL {1516public static void main(String[] args) throws IOException {17String clientRegion = "*** Client region ***";18String bucketName = "*** Bucket name ***";19String objectKey = "*** Object key ***";2021try {22AmazonS3 s3Client = AmazonS3ClientBuilder.standard()23.withRegion(clientRegion)24.withCredentials(new ProfileCredentialsProvider())25.build();2627// Set the presigned URL to expire after one hour.28java.util.Date expiration = new java.util.Date();29long expTimeMillis = expiration.getTime();30expTimeMillis += 1000 * 60 * 60;31expiration.setTime(expTimeMillis);3233// Generate the presigned URL.34System.out.println("Generating pre-signed URL.");35GeneratePresignedUrlRequest generatePresignedUrlRequest =36new GeneratePresignedUrlRequest(bucketName, objectKey)37.withMethod(HttpMethod.GET)38.withExpiration(expiration);39URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);4041System.out.println("Pre-Signed URL: " + url.toString());42}43catch(AmazonServiceException e) {44// The call was transmitted successfully, but Amazon S3 couldn't process45// it, so it returned an error response.46e.printStackTrace();47}48catch(SdkClientException e) {49// Amazon S3 couldn't be contacted for a response, or the client50// couldn't parse the response from Amazon S3.51e.printStackTrace();52}53}54}5556