Instale e use o Alibaba Cloud Domain Names SDK for Java para chamar operações de API, como o envio de tarefas de registro de domínio.
Pré-requisitos
Crie um par de AccessKey de usuário RAM. Recomenda-se usar um usuário RAM em vez de uma conta Alibaba Cloud, pois o vazamento do AccessKey da conta expõe todos os recursos. Para saber como obter o par de AccessKey, consulte Create an AccessKey.
-
O usuário RAM precisa ter permissões de gerenciamento de nomes de domínio. Este exemplo usa a política de sistema AliyunDomainFullAccess.
-
Políticas de sistema:
AliyunDomainFullAccess: permissões completas sobre Domain Names.
AliyunDomainReadonlyAccess: acesso somente leitura ao registro e gerenciamento de domínios.
-
Também é possível usar uma política personalizada.
Para mais informações sobre como crie uma política personalizada, consulte Create a custom policy.
-
Configure o par de AccessKey do usuário RAM nas variáveis de ambiente. Para mais informações, consulte Configure environment variables on Linux, macOS, and Windows.
Instale o SDK
-
Adicione um repositório ao arquivo de configuração do 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> -
Adicione a dependência a seguir na seção
<dependencies>do arquivo pom.xml do seu projeto e atualize o Maven.<dependency> <groupId>com.aliyun</groupId> <artifactId>domain20180129</artifactId> <version>3.15.1</version> </dependency>
Usar o SDK
1. Inicializar um client
Os SDKs da Alibaba Cloud oferecem suporte a diversos tipos de credenciais para inicialização do client, como pares de AccessKey e tokens STS. Para mais informações, consulte Gerencie credentials. Este exemplo usa um 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 um objeto de requisição
Localize a operação de API desejada e seus parâmetros na API Reference e construa o objeto de requisição.
Os objetos de requisição seguem a convenção de nomenclatura {Nome da API}Request. Por exemplo, SaveSingleTaskForCreatingOrderActivate usa SaveSingleTaskForCreatingOrderActivateRequest.
SaveSingleTaskForCreatingOrderActivateRequest request = new SaveSingleTaskForCreatingOrderActivateRequest()
.setDomainName("example.com");
3. Chamar a operação
Os objetos de resposta seguem a convenção de nomenclatura {Nome da API}Response. Por exemplo, SaveSingleTaskForCreatingOrderActivate retorna SaveSingleTaskForCreatingOrderActivateResponse.
// Specify the runtime parameters.
RuntimeOptions runtime = new RuntimeOptions();
SaveSingleTaskForCreatingOrderActivateResponse response = client.saveSingleTaskForCreatingOrderActivateWithOptions(request, runtime);
4. Tratar exceções
O SDK for Java lança dois tipos de exceção: TeaUnretryableException e TeaException.
TeaUnretryableException: lançada quando erros de rede persistem após esgotar todas as tentativas de nova chamada.
-
TeaException: lançada em caso de erros de lógica de negócio.
ImportanteEste exemplo imprime os erros apenas para fins de demonstração. Em produção, trate as exceções adequadamente — reporte erros, registre detalhes em log e implemente novas tentativas para garantir a estabilidade do 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. Exemplo 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();
}
}
}