Después de cargar objetos en un bucket, Object Storage Service (OSS) genera automáticamente URL que incluyen el endpoint público del bucket para dichos objetos. Estas URL permiten acceder a los objetos. Si desea acceder a los objetos mediante un nombre de dominio personalizado, debe agregar un registro CNAME para asignar el nombre de dominio personalizado al bucket donde se almacenan los objetos.
Notas de uso
En este tema se utiliza el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints compatibles, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información, consulte 配置访问凭证.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como el uso de un dominio personalizado o la autenticación con credenciales de Security Token Service (STS), consulte Client configuration.
Creación de un token de CNAME
A continuación se muestra un ejemplo de código para crear un token de CNAME:
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 {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the custom domain name.
String domain = "www.example.com";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a CNAME token.
CreateBucketCnameTokenRequest request = new CreateBucketCnameTokenRequest(bucketName);
// Specify a custom domain name.
request.setDomain(domain);
CreateBucketCnameTokenResult result = ossClient.createBucketCnameToken(request);
// Display the name of the CNAME record.
System.out.println(result.getCname());
// Display the CNAME token that is returned by OSS.
System.out.println(result.getToken());
// Display the point in time when the CNAME token expires.
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();
}
}
}
}
Consulta de un token de CNAME
A continuación se muestra un ejemplo de código para consultar un token de CNAME:
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 {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the custom domain name.
String domain = "www.example.com";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Query the CNAME token.
GetBucketCnameTokenRequest request = new GetBucketCnameTokenRequest(bucketName);
request.setDomain(domain);
GetBucketCnameTokenResult result = ossClient.getBucketCnameToken(request);
// Display the name of the CNAME record.
System.out.println(result.getCname());
// Display the CNAME token that is returned by OSS.
System.out.println(result.getToken());
// Display the point in time when the CNAME token expires.
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();
}
}
}
}
Adición de un registro CNAME
A continuación se muestra un ejemplo de código para agregar un registro CNAME a un bucket:
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 {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the custom domain name.
String domain = "www.example.com";
// Specify the path of the certificate that you want to bind to the domain name.
String crtPath = "oss/generic.testputcname.com.crt";
// Specify the path of the private key of the certificate.
String keyPath = "oss/generic.testputcname.com.key";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
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()
// Specify the public key of the certificate.
.withPublicKey(pubKey)
// Specify the private key of the certificate.
.withPrivateKey(priKey)
/*// Specify the ID of the certificate.
.withPreviousId("493****-cn-hangzhou")
// Specify whether to 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();
}
}
}
}
Consulta de un registro CNAME
A continuación se muestra un ejemplo de código para consultar un registro CNAME de un 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 {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Query the CNAME record.
List<CnameConfiguration> cnameConfigurations = ossClient.getBucketCname(bucketName);
if(cnameConfigurations.get(0) != null){
// Display the ID of the certificate.
System.out.println(cnameConfigurations.get(0).getCertId());
// Display the custom domain name.
System.out.println(cnameConfigurations.get(0).getDomain());
// Display the source of the certificate.
System.out.println(cnameConfigurations.get(0).getCertType());
// Display the status of the domain name.
System.out.println(cnameConfigurations.get(0).getStatus());
// Display the status of the certificate.
System.out.println(cnameConfigurations.get(0).getCertStatus());
// Display the point in time when the custom domain name is mapped to the bucket.
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();
}
}
}
}
Eliminación de un registro CNAME
A continuación se muestra un ejemplo de código para eliminar el registro CNAME que apunta a un bucket:
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 {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the custom domain name.
String domain = "www.example.com";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
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();
}
}
}
}
Referencias
Para obtener más información sobre la operación de API que permite crear un token de CNAME para la verificación de propiedad del nombre de dominio, consulte CreateCnameToken.
Para obtener más información sobre la operación de API que permite consultar un token de CNAME, consulte GetCnameToken.
Para obtener más información sobre la operación de API que permite agregar un registro CNAME, consulte PutCname.
Para obtener más información sobre la operación de API que permite consultar un registro CNAME, consulte ListCname.
Para obtener más información sobre la operación de API que permite eliminar un registro CNAME, consulte DeleteCname.