Help Center/ Object Storage Service/ Android SDK Developer Guide (Ally Region)/ CORS/ Setting CORS Rules
Updated on 2026-01-16 GMT+08:00
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.
This example sets a CORS rule for bucket bucketname.
The example code is as follows:
// Hard-coded or plaintext AK/SK are risky. For security purposes, encrypt your AK/SK and store them in the configuration file or environment variables. In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); String endPoint = "https://your-endpoint"; // 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-domain 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);
- AllowedOrigins and AllowedHeaders respectively can contain up to one wildcard character (*). The wildcard character (*) indicates that all origins or headers are allowed.
Parent topic: CORS
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
The system is busy. Please try again later.
For any further questions, feel free to contact us through the chatbot.
Chatbot