All Products
Search
Document Center

Object Storage Service:Bind custom domain names (Java SDK V1)

Last Updated:Nov 26, 2025

After you upload an object to a bucket, Object Storage Service (OSS) automatically generates a URL that you can use to access the object. This URL contains the public endpoint of the bucket. To access objects using a custom domain name, you must add a CNAME record to bind the custom domain name to the bucket where the objects are stored.

Notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, see OSS regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Configuration examples for common scenarios.

Create a CnameToken

The following code shows how to create a CnameToken.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.CreateBucketCnameTokenRequest;
import com.aliyun.oss.model.CreateBucketCnameTokenResult;

public class Demo {

    public static void main(String[] args) throws Exception {
        // This example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the custom domain name.
        String domain = "www.example.com";
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create a CnameToken.
            CreateBucketCnameTokenRequest request = new CreateBucketCnameTokenRequest(bucketName);
            // Set the custom domain name.
            request.setDomain(domain);
            CreateBucketCnameTokenResult result = ossClient.createBucketCnameToken(request);
            // Print the CNAME that is bound.
            System.out.println(result.getCname());
            // Print the CnameToken returned by OSS.
            System.out.println(result.getToken());
            // Print the expiration time of the CnameToken.
            System.out.println(result.getExpireTime());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Get a CnameToken

The following code shows how to retrieve a CnameToken.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetBucketCnameTokenRequest;
import com.aliyun.oss.model.GetBucketCnameTokenResult;

public class Demo {

    public static void main(String[] args) throws Exception {
        // This example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the custom domain name.
        String domain = "www.example.com";
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Get the CnameToken.
            GetBucketCnameTokenRequest request = new GetBucketCnameTokenRequest(bucketName);
            request.setDomain(domain);
            GetBucketCnameTokenResult result = ossClient.getBucketCnameToken(request);
            // Print the CNAME that is bound.
            System.out.println(result.getCname());
            // Print the CnameToken returned by OSS.
            System.out.println(result.getToken());
            // Print the expiration time of the CnameToken.
            System.out.println(result.getExpireTime());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Add a CNAME record

The following code shows how to add a CNAME record.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.AddBucketCnameRequest;
import com.aliyun.oss.model.CertificateConfiguration;
import java.io.FileInputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // This example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the custom domain name.
        String domain = "www.example.com";
        // Specify the certificate path.
        String crtPath = "oss/generic.testputcname.com.crt";
        // Specify the private key path.
        String keyPath = "oss/generic.testputcname.com.key";
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {            
            String pubKey = IOUtils.readStreamAsString(new FileInputStream(crtPath), "utf8");
            String priKey = IOUtils.readStreamAsString(new FileInputStream(keyPath), "utf8");
            // Add a CNAME record.
            AddBucketCnameRequest request = new AddBucketCnameRequest(bucketName)
                    .withDomain(domain)
                    .withCertificateConfiguration(new CertificateConfiguration()
                            // Set the public key of the certificate.
                            .withPublicKey(pubKey)
                            // Set the private key of the certificate.
                            .withPrivateKey(priKey)
                            /*// Set the current certificate ID.
                            .withPreviousId("493****-cn-hangzhou")
                            // Specify whether to forcibly overwrite the certificate.
                            .withForceOverwriteCert(false)
                            // Specify whether to delete the certificate.
                            .withDeleteCertificate(false)*/);
            ossClient.addBucketCname(request);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

View CNAME records

The following code shows how to view the CNAME records of a bucket.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.CnameConfiguration;
import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // This example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Get the CNAME records.
            List<CnameConfiguration> cnameConfigurations = ossClient.getBucketCname(bucketName);
            if(cnameConfigurations.get(0) != null){
                // Print the certificate ID.
                System.out.println(cnameConfigurations.get(0).getCertId());
                // Print the custom domain name.
                System.out.println(cnameConfigurations.get(0).getDomain());
                // Print the certificate source.
                System.out.println(cnameConfigurations.get(0).getCertType());
                // Print the status of the domain name.
                System.out.println(cnameConfigurations.get(0).getStatus());
                // Print the certificate status.
                System.out.println(cnameConfigurations.get(0).getCertStatus());
                // Print the time when the custom domain name was bound.
                System.out.println(cnameConfigurations.get(0).getLastMofiedTime());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Delete a CNAME record

The following code shows how to delete a CNAME record.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;

public class Demo {

    public static void main(String[] args) throws Exception {
        // This example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the custom domain name.
        String domain = "www.example.com";
        // Specify the region where the bucket is located. This example uses cn-hangzhou, which indicates the China (Hangzhou) region.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Delete the CNAME record.
            ossClient.deleteBucketCname(bucketName, domain);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

References

  • For more information about the API operation to create a CnameToken for domain ownership verification, see CreateCnameToken.

  • For more information about the API operation to retrieve a CnameToken, see GetCnameToken.

  • For more information about the API operation to add a CNAME record, see PutCname.

  • For more information about the API operation to view CNAME records, see ListCname.

  • For more information about the API operation to delete a CNAME record, see DeleteCname.