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

unable to upload with presigned url on aws s3 with java sdk

我收到预签名 URL 上传到 S3。当我上传下面的代码时,我收到 403 状态响应。我尝试在 Web 控制台上将存储桶策略设置为 public,但这并没有解决问题。关于如何解决问题的任何其他见解?我还尝试将 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);

预签名 url:

  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;
    }

如前所述,已签名的 Url 应该与您接下来要执行的操作完全匹配。

您的 pre-signed Url 是通过 GET 操作创建的,这就是上传 PUT 操作失败并出现拒绝访问错误的原因。

尝试将 withMethod 更新为 PUT。

GeneratePresignedUrlRequest generatePresignedUrlRequest =
                new GeneratePresignedUrlRequest(bucketName, objectKey)
                        .withMethod(HttpMethod.PUT)
                        .withExpiration(expiration);