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