KMSインスタンスSDKクライアントが初期化されると、クライアントを使用してGetSecretValue APIを呼び出し、シークレット値を取得できます。 このトピックでは、このプロセスのコード例を示します。
完全なコード例
GetSecretValue APIを呼び出して、シークレット値を取得します。
GitHubで入手可能なソースコード: GetSecretValueSample.java
コード例の分析
クライアントの初期化
詳細については、「クライアントの初期化」をご参照ください。
import com.aliyun.dkms.gcs.openapi.models.Config;
import com.aliyun.dkms.gcs.sdk.Client;
public static void initClient() throws Exception {
// The connection protocol. Set the value to https. The KMS instance service only allows access through the HTTPS protocol.
Config config = new Config();
config.setProtocol("https");
// Client key.
config.setClientKeyFile("<CLIENT_KEY_FILE>");
// Client key security token.
config.setPassword("<PASSWORD>");
// The endpoint of your KMS instance. Set the value in the following format: <ID of your KMS instance >.cryptoservice.kms.aliyuncs.com.
config.setEndpoint("<ENDPOINT>");
// The certificate authority (CA) certificate of the KMS instance. You can specify the path to the CA certificate file or enter the content of the CA certificate.
config.setCaFilePath("<CA_CERTIFICATE_PATH>");
// Alternatively, set the content of the CA certificate of the KMS instance
//config.setCa("<CA_CERTIFICATE_CONTENT");
client = new Client(config);
}GetSecretValue APIを呼び出して、シークレット値を取得します。
/**
* Example of obtaining credential
* @param secretName
*/
private static void getSecretValueSample(String secretName) {
GetSecretValueRequest request = new GetSecretValueRequest()
.setSecretName(secretName);
try {
// If you need to ignore the server certificate, you can use the commented code here to invoke
//RuntimeOptions runtimeOptions = new RuntimeOptions();
//runtimeOptions.setIgnoreSSL(true);
//GetSecretValueResponse getSecretValueResponse = client.getSecretValueWithOptions(request, runtimeOptions);
GetSecretValueResponse getSecretValueResponse = client.getSecretValue(request);
System.out.printf("SecretName: %s%n", getSecretValueResponse.getSecretName());
// System.out.printf("SecretData: %s%n", getSecretValueResponse.getSecretData());
System.out.printf("VersionStages: %s%n", getSecretValueResponse.getVersionStages());
System.out.printf("RequestId: %s%n", getSecretValueResponse.getRequestId());
} catch (Exception e) {
if (e instanceof TeaException) {
System.out.printf("Code: %s%n", ((TeaException) e).getCode());
System.out.printf("Message: %s%n", ((TeaException) e).getMessage());
System.out.printf("HttpCode: %s%n", ((TeaException) e).getData().get("httpCode"));
System.out.printf("HostId: %s%n", ((TeaException) e).getData().get("hostId"));
System.out.printf("RequestId: %s%n", ((TeaException) e).getData().get("requestId"));
}
e.printStackTrace();
}
}
}