最近更新时间:2022-07-25
本文介绍如何进行跨域资源共享。
跨域资源共享(Cross-origin resource sharing,简称CORS)允许Web端的应用程序访问不属于本域的资源。UOS提供跨域资源共享接口,方便您控制跨域访问的权限。
以下代码用于设置、获取和删除跨域资源共享规则:
public void testBucketCORSS() { // Create two CORS rules. List rule1AM.add(CORSRule.AllowedMethods.PUT); rule1AM.add(CORSRule.AllowedMethods.POST); rule1AM.add(CORSRule.AllowedMethods.DELETE); CORSRule rule1 = new CORSRule().withId("CORSRule1").withAllowedMethods(rule1AM) .withAllowedOrigins(Arrays.asList("http://*.example.com")); List rule2AM.add(CORSRule.AllowedMethods.GET); CORSRule rule2 = new CORSRule().withId("CORSRule2").withAllowedMethods(rule2AM) .withAllowedOrigins(Arrays.asList("*")).withMaxAgeSeconds(3000) .withExposedHeaders(Arrays.asList("x-amz-server-side-encryption")); List rules.add(rule1); rules.add(rule2); BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration(); configuration.setRules(rules); try { // Add the configuration to the bucket. s3.setBucketCrossOriginConfiguration(bucketName, configuration); // Retrieve and display the configuration. configuration = s3.getBucketCrossOriginConfiguration(bucketName); printCORSConfiguration(configuration); // Add another new rule. List rule3AM.add(CORSRule.AllowedMethods.HEAD); CORSRule rule3 = new CORSRule().withId("CORSRule3").withAllowedMethods(rule3AM) .withAllowedOrigins(Arrays.asList("http://www.example.com")); rules = configuration.getRules(); rules.add(rule3); configuration.setRules(rules); s3.setBucketCrossOriginConfiguration(bucketName, configuration); // Verify that the new rule was added by checking the number of rules in the configuration. configuration = s3.getBucketCrossOriginConfiguration(bucketName); System.out.println("Expected # of rules = 3, found " + configuration.getRules().size()); // Delete the configuration. s3.deleteBucketCrossOriginConfiguration(bucketName); System.out.println("Removed CORS configuration."); // Retrieve and display the configuration to verify that it was // successfully deleted. configuration = s3.getBucketCrossOriginConfiguration(bucketName); printCORSConfiguration(configuration); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); } } |