如何使用 URL 和 2.x Java SDK 获取 S3 对象?

How to get an S3 object using a URL and the 2.x Java SDK?

我正在使用 2.x AWS Java SDK (https://docs.aws.amazon.com/sdk-for-java/index.html)。我需要使用友好的 HTTP URL(例如 https://bucket.s3.region.amazonaws.com/keyhttps://s3.region.amazonaws.com/bucket/key)获取 S3 对象。

旧版 SDK 包含一个 AmazonS3URI class,可以解析 URL 并提取存储桶和密钥。 2.x SDK 是否包含类似的功能,或者我应该使用 Java 的 URI class 来解析 URL?

目前还没有办法用 SDK 做到这一点,但是 it might be available in the future。同时,您可以使用 Java 的 URI class 编写自己的代码,或者使用旧 SDK 中的 AmazonS3URI 并希望它继续工作。

这是我使用 java.net 中的 URI 所做的:

URI uri = new URI(s3Url);

String bucketName = uri.getHost();

// remove the first "/"
String prefix = uri.getPath().substring(1);

扩展@Bao Pham 的回答,使用 new URI(s3Url) 需要添加 try/catch,而如果您使用 URI.create(s3Url),则不需要它。我还发现使用已解析部分中的 S3ObjectId 来提高可重用性很有用。

public class S3Url {
    public static S3ObjectId decode(String urlStr) {
        URI uri = URI.create(urlStr);
        return new S3ObjectId(uri.getHost(), uri.getPath().substring(1));
    }
}