我正在尝试连接到S3存储桶并下载文件,但是代码抛出异常:

在我的代码中

ProfileCredentialsProvider pcp = new ProfileCredentialsProvider("assumed_role");
        bucketName = "dev-data-extract-service-bucket";
s3Client = AmazonS3ClientBuilder.standard().withCredentials(pcp).withRegion(Regions.US_EAST_1.toString()).build();

我在调用以下行时得到NullPointerException异常:
fullObject = s3Client.getObject(new GetObjectRequest(bucketName, "TR09_20190205.detail"));

原因是端点中的主机值为空
这是来自AmazonS3Client类
private boolean isStandardEndpoint(URI endpoint) {
        return endpoint.getHost().endsWith("s3.amazonaws.com");
}

接下来是堆栈跟踪

[main] DEBUG com.amazonaws.AmazonWebServiceClient-内部日志记录
成功配置为Commons logger:true 15:43:45.183 [main]
DEBUG com.amazonaws.metrics.AwsSdkMetrics-管理员已注册mbean
在com.amazonaws.management:type=AwsSdkMetrics 15:43:45.952下[主要]
调试com.amazonaws.monitoring.CsmConfigurationProviderChain-无法
从加载配置
com.amazonaws.monitoring.EnvironmentVariableCsmConfigurationProvider@169e6180:
无法从环境加载客户端监视配置
变数! 15:43:45.952 [main]调试
com.amazonaws.monitoring.CsmConfigurationProviderChain-无法执行
从加载配置
com.amazonaws.monitoring.SystemPropertyCsmConfigurationProvider@35aea049:
无法从系统加载客户端监视配置
属性变量! 15:43:45.952 [java-sdk-http-connection-reaper]
调试org.apache.http.impl.conn.PoolingHttpClientConnectionManager-
关闭连接空闲时间超过60000 MILLISECONDS 15:43:45.952
[main] DEBUG com.amazonaws.monitoring.CsmConfigurationProviderChain-
无法从中加载配置
com.amazonaws.monitoring.ProfileCsmConfigurationProvider@611889f4:
无法在线程“主”中加载配置文件异常
java.lang.NullPointerException在
com.amazonaws.services.s3.AmazonS3Client.isStandardEndpoint(AmazonS3Client.java:3772)

com.amazonaws.services.s3.AmazonS3Client.noExplicitRegionProvided(AmazonS3Client.java:3767)

com.amazonaws.services.s3.AmazonS3Client.bucketRegionShouldBeCached(AmazonS3Client.java:4505)

com.amazonaws.services.s3.AmazonS3Client.shouldPerformHeadRequestToFindRegion(AmazonS3Client.java:4501)

com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4426)

com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4390)

com.amazonaws.services.s3.AmazonS3Client.getAcl(AmazonS3Client.java:3573)

com.amazonaws.services.s3.AmazonS3Client.getBucketAcl(AmazonS3Client.java:1186)

com.amazonaws.services.s3.AmazonS3Client.getBucketAcl(AmazonS3Client.java:1176)

com.amazonaws.services.s3.AmazonS3Client.doesBucketExistV2(AmazonS3Client.java:1312)
在.AWSHelper.downloadFromS3Bucket(AWSHelper.java:32)在
.AWSHelper.main(AWSHelper.java:59)

最佳答案

我认为您的问题源于您设定区域的方式。我认为该区域解析为null,这导致您的端点为null。

代替:

s3Client = AmazonS3ClientBuilder.standard().withCredentials(pcp).withRegion(Regions.US_EAST_1.toString()).build();

尝试:
s3Client = AmazonS3ClientBuilder.standard().withCredentials(pcp).withRegion(Regions.US_EAST_1).build();

Regions类不会覆盖toString()方法,因此它不会返回区域名称,这是您的代码按原样工作所必需的。

10-04 11:36