无法使用Java sdk在AWS S3上使用预签名的URL上传

时间:2019-06-12 16:10:46

标签: java amazon-web-services amazon-s3 aws-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);

预签名网址:

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

1 个答案:

答案 0 :(得分:1)

如前所述,已签名的网址应与下一步要完全匹配。

您的预签名网址是使用GET操作创建的,这就是为什么上载PUT操作失败并显示访问被拒绝错误的原因。

尝试将withMethod更新为PUT。

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