我收到一个要上传到 S3 的预签名 URL。当我上传下面的代码时,我收到 403 状态响应。我尝试在 Web 控制台上将存储桶策略设置为公开,但这并没有解决问题。关于如何解决该问题还有其他见解吗?我还尝试将 ACL 添加到 PublicREADWRITE。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
OutputStream out = connection.getOutputStream();
// OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
//out.write("This text uploaded as an object via presigned URL.");
byte[] boundaryBytes = Files.readAllBytes(Paths.get(edmFile));
out.write(boundaryBytes);
out.close();
// Check the HTTP response code. To complete the upload and make the object available,
// you must interact with the connection object in some way.
int responseCode = connection.getResponseCode();
System.out.println("HTTP response code: " + responseCode);
预签名网址:
private URL getUrl(String bucketName, String objectKey) {
String clientRegion = "us-east-1";
java.util.Date expiration = new java.util.Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += 1000 * 60 * 10;
expiration.setTime(expTimeMillis);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(clientRegion)
.build();
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.GET)
.withExpiration(expiration);
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
System.out.println("Pre-Signed URL: " + url.toString());
return url;
}
最佳答案
正如所讨论的,签名的网址应该与您下一步想要执行的操作完全匹配。
您的预签名网址是通过 GET
操作创建的,这就是上传 PUT
操作失败并出现访问被拒绝错误的原因。
尝试将 withMethod 更新为 PUT。
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.PUT)
.withExpiration(expiration);
关于java - 无法使用 java sdk 在 aws s3 上使用预签名 url 上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56566427/