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

Viewed 7142

I'm using the 2.x AWS Java SDK (https://docs.aws.amazon.com/sdk-for-java/index.html). I need to get an S3 object using the friendly HTTP URL (e.g. https://bucket.s3.region.amazonaws.com/key or https://s3.region.amazonaws.com/bucket/key).

The old SDK included an AmazonS3URI class that could parse a URL and extract the bucket and key. Does the 2.x SDK include similar functionality, or should I use Java's URI class to parse the URL?

4 Answers

This is what I did using URI from java.net:

URI uri = new URI(s3Url);

String bucketName = uri.getHost();

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

There isn't a way to do it with the SDK yet, but it might be available in the future. In the meantime, you can write your own code using Java's URI class, or use AmazonS3URI from the old SDK and hope it keeps working.

Expanding upon @Bao Pham's answer, using new URI(s3Url) requires adding a try/catch, while if you use URI.create(s3Url), you don't need it. I also found it useful to use a S3ObjectId out of the parsed parts for re-usability.

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