Alibaba Cloud SDK for Java V2.0 prend en charge les appels d'API génériques. Cette fonctionnalité permet d'appeler n'importe quelle opération OpenAPI sans installer les SDK spécifiques à chaque service.
Caractéristiques
Léger : seule la bibliothèque principale d'Alibaba Cloud SDK est requise. Vous n'avez pas besoin d'installer le SDK de chaque service.
Simple d'utilisation : construisez des paramètres de requête communs, utilisez un client universel pour envoyer les requêtes et recevez des réponses dans des formats standardisés.
Pour plus d'informations, consultez Appels génériques et appels spécialisés.
Remarques sur l'utilisation
Avant d'appeler une API de manière générique, consultez les métadonnées de l'opération d'API pour obtenir le style de l'API, les paramètres de requête et l'URL.
Installer le SDK
Exécutez la commande suivante pour installer la bibliothèque principale d'Alibaba Cloud SDK V2.0 pour .NET. Pour obtenir la dernière version, reportez-vous à AlibabaCloud.OpenApiClient.
dotnet add package AlibabaCloud.OpenApiClient --version 0.1.13
Appeler une opération d'API
Initialiser un client de requête
Créez un objet AlibabaCloud.OpenApiClient.Client pour initialiser un client de requête. Vous pouvez également utiliser l'outil Credentials pour gérer vos identifiants. Pour plus d'informations, consultez Gestion des identifiants d'accès.
public static AlibabaCloud.OpenApiClient.Client CreateClient()
{
AlibabaCloud.OpenApiClient.Models.Config config =
new AlibabaCloud.OpenApiClient.Models.Config
{
// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID.
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET.
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
};
config.Endpoint = "ecs-cn-hangzhou.aliyuncs.com";
return new AlibabaCloud.OpenApiClient.Client(config);
}
// Use the Credentials tool.
// public static AlibabaCloud.OpenApiClient.Client CreateClient()
// {
// // Use an AccessKey pair to initialize the Credentials client.
// Aliyun.Credentials.Models.Config credentialsConfig =
// new Aliyun.Credentials.Models.Config()
// {
// // The credential type.
// Type = "access_key",
// // Obtain the AccessKey ID from the environment variable.
// AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// // Obtain the AccessKey secret from the environment variable.
// AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
// };
// Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
// AlibabaCloud.OpenApiClient.Models.Config config =
// new AlibabaCloud.OpenApiClient.Models.Config
// {
// Credential = credentialClient,
// Endpoint = "ecs-cn-hangzhou.aliyuncs.com",
// };
// return new AlibabaCloud.OpenApiClient.Client(config);
// }
Configurer les informations de l'opération d'API
Utilisez AlibabaCloud.OpenApiClient.Models.Params pour spécifier le style de l'API, sa version et la méthode de requête. L'exemple suivant appelle l'opération DescribeInstanceTypeFamilies.
AlibabaCloud.OpenApiClient.Models.Params params_ =
new AlibabaCloud.OpenApiClient.Models.Params
{
Action = "DescribeInstanceTypeFamilies", // The API operation.
Version = "2014-05-26", // The version number of the API operation.
Protocol = "HTTPS", // The request protocol. Valid values: HTTP and HTTPS. We recommend that you use HTTPS.
Method = "POST", // The request method.
AuthType = "AK", // The authentication type. Use the default type. If the API operation supports anonymous requests, you can specify the Anonymous parameter to initiate an anonymous request.
Style = "RPC", // The API style, such as remote procedure call (RPC) and resource-oriented architecture (ROA).
Pathname = "/", // The URL of the API operation. The default path of an RPC-style operation is /. You can obtain the URL of an ROA-style operation from the data.path parameter in the API metadata.
ReqBodyType = "json", // The type of request body. Valid values: json and formData.
BodyType = "json", // The response format. Valid value: json.
};
Configurer les paramètres de requête
Utilisez AlibabaCloud.OpenApiClient.Models.OpenApiRequest pour configurer les paramètres de requête. Selon les métadonnées de l'API, transmettez ces paramètres via une chaîne de requête, un corps de requête ou un flux. Par exemple, le paramètre RegionId de l'opération DescribeInstanceTypeFamilies est défini par {"name":"RegionId","in":"query",...}} dans les métadonnées. La mention "in":"query" indique que RegionId doit être passé dans une chaîne de requête.
|
Méthode |
Description |
|
Query |
Transmettez le paramètre dans la chaîne de requête lorsque les métadonnées indiquent |
|
Body |
Incluez le paramètre dans le corps de la requête si les métadonnées spécifient |
|
Stream |
Pour transférer des fichiers, configurez le paramètre Stream afin de passer les flux de fichiers. |
// Method 1: Configure a query string.
Dictionary<string, object> queries = new Dictionary<string, object>() { };
queries["RegionId"] = "cn-hangzhou";
AlibabaCloud.OpenApiClient.Models.OpenApiRequest request =
new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
{
Query = AlibabaCloud.OpenApiUtil.Client.Query(queries),
};
// // Method 2: Configure the body and set reqBodyType to json.
// Dictionary<string, object> body = new Dictionary<string, object>()
// {
// { "param1", "value1" },
// { "param2", "value2" },
// };
// AlibabaCloud.OpenApiClient.Models.OpenApiRequest request =
// new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
// {
// Body = AlibabaCloud.OpenApiUtil.Client.Query(body),
// };
// // Method 3: Configure the body and set reqBodyType to formData.
// Dictionary<string, object> formData = new Dictionary<string, object>()
// {
// { "param1", "value1" },
// { "param2", "value2" },
// };
// AlibabaCloud.OpenApiClient.Models.OpenApiRequest request =
// new AlibabaCloud.OpenApiClient.Models.OpenApiRequest { Body = formData };
// // Method 4: Configure the Stream parameter to pass file streams
// AlibabaCloud.OpenApiClient.Models.OpenApiRequest request =
// new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
// {
// Stream = "<FILE_STREAM>",
// };
Envoyer une requête
Utilisez AlibabaCloud.OpenApiClient.Client pour envoyer une requête en appelant la méthode CallApi. Vous pouvez également configurer des paramètres d'exécution tels que le délai d'expiration et les paramètres de proxy. Pour plus d'informations, consultez Configuration avancée.
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
var response = client.CallApi(params_, request, runtime);
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
Console.WriteLine(response["statusCode"]);
Exemples de code
Exemple : appeler une opération d'API de style RPC
L'exemple ci-dessous illustre un appel générique en appelant l'opération DescribeInstanceTypeFamilies d'Elastic Compute Service (ECS).
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
public static AlibabaCloud.OpenApiClient.Client CreateClient()
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID.
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET.
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
};
config.Endpoint = "ecs-cn-hangzhou.aliyuncs.com";
return new AlibabaCloud.OpenApiClient.Client(config);
}
public static AlibabaCloud.OpenApiClient.Models.Params CreateApiInfo()
{
AlibabaCloud.OpenApiClient.Models.Params params_ = new AlibabaCloud.OpenApiClient.Models.Params
{
// The name of the API operation.
Action = "DescribeInstanceTypeFamilies",
// The version number of the API operation.
Version = "2014-05-26",
// The protocol of the API operation.
Protocol = "HTTPS",
// The HTTP method of the API operation.
Method = "POST",
AuthType = "AK",
Style = "RPC",
// The path of the API operation.
Pathname = "/",
// The format of the request body.
ReqBodyType = "json",
// The format of the response body.
BodyType = "json",
};
return params_;
}
public static void Main(string[] args)
{
AlibabaCloud.OpenApiClient.Client client = CreateClient();
AlibabaCloud.OpenApiClient.Models.Params params_ = CreateApiInfo();
// query params
Dictionary<string, object> queries = new Dictionary<string, object>(){};
queries["RegionId"] = "cn-hangzhou";
// runtime options
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
AlibabaCloud.OpenApiClient.Models.OpenApiRequest request = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
{
Query = AlibabaCloud.OpenApiUtil.Client.Query(queries),
};
// If you copy and run the sample code, write your code to display the response of the operation.
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
var response = client.CallApi(params_, request, runtime);
Console.WriteLine(response["statusCode"]);
}
}
}
Exemple : appeler une opération d'API de style RESTful (ROA)
L'exemple suivant effectue un appel générique vers l'opération DescribeClustersV1 d'ACK.
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
public static AlibabaCloud.OpenApiClient.Client CreateClient()
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID.
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET.
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
};
config.Endpoint = "cs.cn-hangzhou.aliyuncs.com";
return new AlibabaCloud.OpenApiClient.Client(config);
}
public static AlibabaCloud.OpenApiClient.Models.Params CreateApiInfo()
{
AlibabaCloud.OpenApiClient.Models.Params params_ = new AlibabaCloud.OpenApiClient.Models.Params
{
// The name of the API operation.
Action = "DescribeClustersV1",
// The version number of the API operation.
Version = "2015-12-15",
// The protocol of the API operation.
Protocol = "HTTPS",
// The HTTP method of the API operation.
Method = "GET",
AuthType = "AK",
Style = "ROA",
// The path of the API operation.
Pathname = "/api/v1/clusters",
// The format of the request body.
ReqBodyType = "json",
// The format of the response body.
BodyType = "json",
};
return params_;
}
public static void Main(string[] args)
{
AlibabaCloud.OpenApiClient.Client client = CreateClient();
AlibabaCloud.OpenApiClient.Models.Params params_ = CreateApiInfo();
// runtime options
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
AlibabaCloud.OpenApiClient.Models.OpenApiRequest request = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest();
// Write your code to display the response of the operation if necessary.
// The response is of the MAP type, which contains the response body, response headers, and HTTP status code.
var response = client.CallApi(params_, request, runtime);
Console.WriteLine(response["statusCode"]);
}
}
}