桶跨域访问设置
跨域资源共享 (CORS) 定义了在一个域中加载的客户端 Web 应用程序与另一个域中的资源交互的方式。利用 CORS 支持,您可以构建丰富的客户端 Web 应用程序,同时可以选择性地允许跨源访问您的资源。
您可以通过 setBucketCrossOriginConfiguration 接口设置桶的跨域访问设置,以下为示例代码:
String bucketName = "<your-bucket-name>";
List<CORSRule.AllowedMethods> rule2AM = new ArrayList<>();
//添加允许的http请求方法
rule2AM.add(CORSRule.AllowedMethods.PUT);
rule2AM.add(CORSRule.AllowedMethods.GET);
rule2AM.add(CORSRule.AllowedMethods.HEAD);
CORSRule rule = new CORSRule().withId("CORSRule").withAllowedMethods(rule2AM)
//添加允许的请求源
.withAllowedOrigins(Arrays.asList("*"))
//添加返回的字段
.withExposedHeaders(Arrays.asList("x-amz-server-side-encryption", "ETag", "x-amz-request-id", "Date",
"Content-Length", "Accept-Ranges", "Access-Control-Allow-Origin"))
//添加允许的请求头
.withAllowedHeaders(Arrays.asList("*"));
List<CORSRule> rules = new ArrayList<>();
rules.add(rule);
BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration();
configuration.setRules(rules);
s3.setBucketCrossOriginConfiguration(bucketName, configuration);
您可以通过 getBucketCrossOriginConfiguration 接口获取桶跨域访问设置,以下为示例代码:
String bucketName = "<your-bucket-name>";
BucketCrossOriginConfiguration bucketCrossOriginConfiguration = s3.getBucketCrossOriginConfiguration(bucketName);
List<CORSRule> rules = bucketCrossOriginConfiguration.getRules();
for(CORSRule rule : rules){
List<String> allowedHeaders = rule.getAllowedHeaders();
List<String> allowedOrigins = rule.getAllowedOrigins();
List<String> exposedHeaders = rule.getExposedHeaders();
List<CORSRule.AllowedMethods> allowedMethods = rule.getAllowedMethods();
}
您可以通过 deleteBucketCrossOriginConfiguration 接口删除桶跨域访问设置,以下为示例代码:
String bucketName = "<your-bucket-name>";
s3.deleteBucketCrossOriginConfiguration(bucketName);