You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWS SDK连接LocalStack S3失败:URL被自动添加桶名

解决AWS Java SDK调用LocalStack S3时桶名被添加到URL前缀的问题

问题根源在于AWS Java SDK默认采用虚拟主机样式构造S3请求(将桶名作为域名前缀,比如http://test.localhost:4566),但LocalStack默认期望路径样式的请求(桶名作为URL路径的一部分,比如http://localhost:4566/test),两者不匹配导致连接失败。

只需在构建S3客户端时强制开启路径样式访问即可解决,修改后的代码如下:

public void testS3() {
  final String localStackS3URL = "http://localhost:4566";
  final String REGION = "us-east-1";
  final AwsClientBuilder.EndpointConfiguration endpoint = new AwsClientBuilder.EndpointConfiguration(localStackS3URL, REGION);

  final AmazonS3 client = AmazonS3ClientBuilder.standard()
          .withEndpointConfiguration(endpoint)
          .withPathStyleAccessEnabled(true) // 关键:开启路径样式访问
          .build();

  if(!client.doesBucketExistV2("test")){
      client.createBucket("test");
  }
}

补充说明:AWS CLI能正常运行是因为它会自动适配LocalStack的Endpoint格式,或者通过--endpoint-url参数自动切换到路径样式,但Java SDK需要显式配置该参数才能兼容。

内容的提问来源于stack exchange,提问作者anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:40:38