场景:在访问amazon S3时遇到报错Exception in thread "main" software.amazon.awssdk.core.exception.SdkClientException: Received an UnknownHostException when attempting to interact with a service. See cause for the exact endpoint that is failing to resolve. If this is happening on an endpoint that previously worked, there may be a network connectivity issue or your DNS cache could be storing endpoints for too long.
// 设置认证信息
static {
AwsCredentials credentials = AwsBasicCredentials.create(accessKeyId, secretAccessKey);
s3Client = S3Client.builder()
.endpointOverride(URI.create(endpoint))
.region(Region.of(region)) // 根据实际情况设置 region
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.build();
}
已解决:问题在设置认证信息时访问S3无法解析端点,主要原因: AWS S3(Simple Storage Service)有两种对象访问路径样式: 虚拟主机路径样式(默认):在虚拟主机路径样式中,S3桶的访问通过URL中的主机名来指定,例如https://bucket-name.s3.amazonaws.com/key-name。 路径样式:在路径样式中,S3桶的访问通过URL路径中的查询参数来指定,例如https://s3.amazonaws.com/bucket-name/key-name。
解决方法:使用.forcePathStyle(true)方法告诉S3客户端,无论是使用默认的虚拟主机路径样式还是路径样式,都强制使用路径样式。
// 设置认证信息
static {
AwsCredentials credentials = AwsBasicCredentials.create(accessKeyId, secretAccessKey);
s3Client = S3Client.builder()
.forcePathStyle(true)
.endpointOverride(URI.create(endpoint))
.region(Region.of(region)) // 根据实际情况设置 region
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.build();
}