• Object Storage Service

obs
  1. Help Center
  2. Object Storage Service
  3. Developer Guide (Java SDK)
  4. CORS
  5. Setting CORS Rules

Setting CORS Rules

You can call ObsClient.setBucketCors to set CORS rules for a bucket. If the bucket is configured with CORS rules, the newly set ones will overwrite the existing ones. Sample code is as follows:

String endPoint = "yourdomainname";
String ak = "*** Provide your Access Key ***";
String sk = "*** Provide your Secret Key ***";
// Create an instance of ObsClient.
ObsClient obsClient = new ObsClient(ak, sk, endPoint);

BucketCors cors = new BucketCors();

List<BucketCorsRule> rules = new ArrayList<BucketCorsRule>();
BucketCorsRule rule = new BucketCorsRule();

ArrayList<String> allowedOrigin = new ArrayList<String>();
// Specify the origin of the cross-origin request.
allowedOrigin.add( "http://www.a.com"); 
allowedOrigin.add( "http://www.b.com"); 
rule.setAllowedOrigin(allowedOrigin);

ArrayList<String> allowedMethod = new ArrayList<String>();
// Specify the request method, which can be GET, PUT, DELETE, POST, or HEAD.
allowedMethod.add("GET");   
allowedMethod.add("HEAD");
allowedMethod.add("PUT");   
rule.setAllowedMethod(allowedMethod);

ArrayList<String> allowedHeader = new ArrayList<String>();
// Specify whether headers specified in Access-Control-Request-Headers in the OPTIONS request can be used.
allowedHeader.add("x-obs-header"); 
rule.setAllowedHeader(allowedHeader);

ArrayList<String> exposeHeader = new ArrayList<String>();
// Specify response headers that users can access using application programs.
exposeHeader.add("x-obs-expose-header");
rule.setExposeHeader(exposeHeader);

// Specify the browser's cache time of the returned results of OPTIONS requests for specific resources, in seconds.
rule.setMaxAgeSecond(10);
rules.add(rule);
cors.setRules(rules);

obsClient.setBucketCors("bucketname", cors);

// Close obsClient.
obsClient.close();
NOTE:

AllowedOrigins and AllowedHeaders respectively can contain up to one wildcard character (*). The wildcard character (*) indicates that all origins or headers are allowed.