Instale y utilice el SDK de Alibaba Cloud Domain Names para Java con el fin de invocar operaciones de la API, como el envío de tareas de registro de dominios.
Requisitos previos
Se ha creado un par de AccessKey para un usuario de RAM. Se recomienda utilizar un usuario de RAM en lugar de una cuenta de Alibaba Cloud, ya que la filtración de un AccessKey de cuenta expone todos los recursos. Para obtener información sobre cómo conseguir el par de AccessKey, consulte Create an AccessKey.
-
El usuario de RAM cuenta con permisos de gestión de nombres de dominio. Este ejemplo utiliza la directiva del sistema AliyunDomainFullAccess.
-
Directivas del sistema:
AliyunDomainFullAccess: permisos completos sobre Domain Names.
AliyunDomainReadonlyAccess: acceso de solo lectura al registro y gestión de dominios.
-
También puede usar una directiva personalizada.
Para más información sobre cómo crear una directiva personalizada, consulte Create a custom policy.
-
El par de AccessKey del usuario de RAM está configurado en variables de entorno. Para más información, consulte Configure environment variables on Linux, macOS, and Windows.
Instalar el SDK
-
Agregue un repositorio a su archivo de configuración de Maven.
<repositories> <repository> <id>sonatype-nexus-staging</id> <name>Sonatype Nexus Staging</name> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> -
Agregue la siguiente dependencia a la sección
<dependencies>del archivo pom.xml de su proyecto y, a continuación, actualice Maven.<dependency> <groupId>com.aliyun</groupId> <artifactId>domain20180129</artifactId> <version>3.15.1</version> </dependency>
Usar el SDK
1. Inicializar un cliente
Los SDK de Alibaba Cloud admiten varios tipos de credenciales para la inicialización del cliente, como pares de AccessKey y tokens de STS. Para más información, consulte Manage credentials. Este ejemplo utiliza un par de AccessKey.
import com.aliyun.domain20180129.Client;
import com.aliyun.teaopenapi.models.Config;
public class Sample {
private static Client createClient() throws Exception {
Config config = new Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
// Specify an endpoint. For information about endpoints, visit https://api.alibabacloud.com/product/Domain.
.setEndpoint("domain.aliyuncs.com");
return new Client(config);
}
}
2. Construir un objeto de solicitud
Localice la operación de la API deseada y sus parámetros en la API Reference y, a continuación, construya el objeto de solicitud.
Los objetos de solicitud siguen la convención de nomenclatura {nombre de la API}Request. Por ejemplo, SaveSingleTaskForCreatingOrderActivate utiliza SaveSingleTaskForCreatingOrderActivateRequest.
SaveSingleTaskForCreatingOrderActivateRequest request = new SaveSingleTaskForCreatingOrderActivateRequest()
.setDomainName("example.com");
3. Invocar la operación
Los objetos de respuesta siguen la convención de nomenclatura {nombre de la API}Response. Por ejemplo, SaveSingleTaskForCreatingOrderActivate devuelve SaveSingleTaskForCreatingOrderActivateResponse.
// Specify the runtime parameters.
RuntimeOptions runtime = new RuntimeOptions();
SaveSingleTaskForCreatingOrderActivateResponse response = client.saveSingleTaskForCreatingOrderActivateWithOptions(request, runtime);
4. Gestionar excepciones
El SDK para Java lanza dos tipos de excepciones: TeaUnretryableException y TeaException.
TeaUnretryableException: se lanza cuando persisten los errores de red tras agotar todos los intentos de reintento.
-
TeaException: se lanza por errores de lógica de negocio.
ImportanteEste ejemplo imprime los errores únicamente con fines demostrativos. En entornos de producción, gestione las excepciones adecuadamente: reporte los errores, registre los detalles e implemente reintentos para garantizar la estabilidad del sistema.
try {
Client client = createClient();
SaveSingleTaskForCreatingOrderActivateRequest request = new SaveSingleTaskForCreatingOrderActivateRequest()
.setDomainName("example.com");
// Specify the runtime parameters.
RuntimeOptions runtime = new RuntimeOptions();
SaveSingleTaskForCreatingOrderActivateResponse response = client.saveSingleTaskForCreatingOrderActivateWithOptions(request, runtime);
} catch (TeaUnretryableException ue) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
ue.printStackTrace();
// Obtain the error message.
System.out.println(ue.getMessage());
// Obtain the request message and query the request information when an error occurs.
System.out.println(ue.getLastRequest());
} catch (TeaException e) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
e.printStackTrace();
// Obtain the error code.
System.out.println(e.getCode());
// Obtain the error message that contains the request ID.
System.out.println(e.getMessage());
// Obtain the detailed error information that is returned by the server.
System.out.println(e.getData());
} catch (Exception e) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
e.printStackTrace();
}
5. Ejemplo completo
import com.aliyun.domain20180129.Client;
import com.aliyun.domain20180129.models.SaveSingleTaskForCreatingOrderActivateRequest;
import com.aliyun.domain20180129.models.SaveSingleTaskForCreatingOrderActivateResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaUnretryableException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
public class Sample {
private static Client createClient() throws Exception {
Config config = new Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
// Specify an endpoint. For information about endpoints, visit https://api.alibabacloud.com/product/Domain.
.setEndpoint("domain.aliyuncs.com");
return new Client(config);
}
public static void main(String[] args_) {
try {
Client client = createClient();
SaveSingleTaskForCreatingOrderActivateRequest request = new SaveSingleTaskForCreatingOrderActivateRequest()
.setDomainName("example.com");
// Specify the runtime parameters.
RuntimeOptions runtime = new RuntimeOptions();
SaveSingleTaskForCreatingOrderActivateResponse response = client.saveSingleTaskForCreatingOrderActivateWithOptions(request, runtime);
} catch (TeaUnretryableException ue) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
ue.printStackTrace();
// Obtain the error message.
System.out.println(ue.getMessage());
// Obtain the request message.
System.out.println(ue.getLastRequest());
} catch (TeaException e) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
e.printStackTrace();
// Obtain the error code.
System.out.println(e.getCode());
// Obtain the error message that contains the request ID.
System.out.println(e.getMessage());
// Obtain the detailed error information that is returned by the server.
System.out.println(e.getData());
} catch (Exception e) {
// Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only.
e.printStackTrace();
}
}
}