java - 无法使用 java sdk 在 aws s3 上使用预签名 url 上传

标签 java amazon-web-services amazon-s3 aws-sdk

我收到一个要上传到 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/

相关文章:

java - org.hibernate.hql.internal.ast.QuerySyntaxException 无效路径

java - 用Java提取SVN数据

amazon-web-services - 如何使用 s3 和 Lightsail Origin 配置 AWS CloudFront

php - 如何避免来自 LinkedIn 的 "HTTP/1.1 999 Request denied"响应?

javascript - 是否可以通过 CloudFront CDN 进行 AWS 内容路由?

java - 调试 ExceptionInInitializerError

java - 无法将 XML 字符串正确转换为 JAXB 对象

amazon-web-services - 使用子域进行服务分段的应用程序负载均衡器

amazon-web-services - Apache Drill 使用 S3 数据源速度慢得无法使用?

amazon-web-services - S3 PUT 的 Boto generate_url 不适用于 IAM 角色?