阿里雲SDK支援一種通用的方式調用OpenAPI,此方式被稱為泛化調用。本文將為您詳細介紹如何使用泛化調用訪問OpenAPI。
特點
輕量:僅需安裝阿里雲核心SDK,無需額外安裝雲產品SDK。
簡單:只需構造通用的請求參數對象,然後利用通用請求用戶端調用通用函數發起請求,調用結果也以通用格式返回。
更多介紹,請參見泛化調用與特化調用。
使用說明
使用泛化調用時,建議先查看OpenAPI中繼資料,擷取OpenAPI的API風格、請求參數、資源路徑等資訊。具體資訊,請參見OpenAPI中繼資料。
安裝核心SDK
在pom.xml中添加以下依賴安裝核心SDK,最新版本請參見Maven Repository。
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-openapi</artifactId>
<version>0.3.10</version>
</dependency>調用OpenAPI
初始化請求用戶端
通過建立com.aliyun.teaopenapi.Client對象初始化請求用戶端,並通過該Client發起OpenAPI調用。在初始化用戶端時,也支援使用Credentials工具,關於Credentials工具的更多資訊,請參見管理訪問憑據。
請求用戶端對象無需手動銷毀,會自動被記憶體回收機制回收。
// 1.初始化請求用戶端
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// 佈建要求地址
config.setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
// 支援通過Config在初始化Client階段設定配置(可選)。
// Client HTTPS 參數設定
// config.setProtocol("HTTPS");
// 地區ID
// config.setRegionId("<regionId>");
// Client代理參數設定
// config.setHttpProxy("http://127.0.0.1:9898");
// config.setHttpsProxy("http://user:password@127.0.0.1:8989");
// config.setNoProxy("127.0.0.1,localhost");
// Client 逾時參數設定
// 連線逾時預設 5 * 1000 毫秒
// config.setConnectTimeout(5000);
// 讀逾時預設 10 * 1000 毫秒
// config.setReadTimeout(10000);
com.aliyun.teaopenapi.Client client = new com.aliyun.teaopenapi.Client(config);
// // 使用Credentials工具
// com.aliyun.credentials.models.Config credentialConfig = new com.aliyun.credentials.models.Config();
// credentialConfig.setType("access_key");
// credentialConfig.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
// credentialConfig.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
// com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// .setCredential(credentialClient)
// .setEndpoint("ecs.cn-hangzhou.aliyuncs.com");
// com.aliyun.teaopenapi.Client client = new com.aliyun.teaopenapi.Client(config);配置OpenAPI資訊
通過com.aliyun.teaopenapi.models.Params配置OpenAPI的基本資料,比如OpenAPI的風格、API版本、請求方式等資訊。以調用DescribeInstanceTypeFamilies介面為例:
com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
.setStyle("RPC") // API風格:RPC或ROA。
.setVersion("2014-05-26") // API版本號碼。
.setMethod("POST") // 要求方法。
.setAction("DescribeInstanceTypeFamilies") // API名稱。
.setPathname("/") // API資源路徑,RPC介面預設"/",ROA介面從OpenAPI中繼資料中data.path擷取資源路徑。
.setProtocol("HTTPS") // 請求協議:HTTPS或HTTP,建議使用HTTPS。
.setAuthType("AK") // 認證類型,預設即可。當OpenAPI支援匿名請求時,您可以傳入 Anonymous 發起匿名請求。
.setReqBodyType("json") // 請求body的類型,支援byte、json、formData。
.setBodyType("json"); // 返回資料格式,支援json。配置請求參數
通過com.aliyun.teaopenapi.models.OpenApiRequest配置請求參數,請求參數支援通過Query、Body或Stream傳參,如何選擇傳參方式可根據中繼資料中的介紹選擇,例如DescribeInstanceTypeFamilies的請求參數RegionId在中繼資料中資訊為{"name":"RegionId","in":"query",...}},其中"in":"query"表示RegionId通過Query傳遞。
傳參方式 | 描述 |
setQuery | 請求參數顯示 |
setBody | 請求參數顯示 |
setStream | 在需要上傳檔案的情境,可通過setStream傳遞檔案流。 |
// 情境一:設定查詢參數(query)
java.util.Map<String, Object> queries = new java.util.HashMap<>();
queries.put("RegionId", "cn-hangzhou");
com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
.setQuery(com.aliyun.openapiutil.Client.query(queries));
// // 情境二:設定body參數,reqBodyType的值為json
// java.util.Map<String, Object> body = new java.util.HashMap<>();
// body.put("param1", "value1");
// body.put("param2", "value2");
// com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
// .setBody(com.aliyun.openapiutil.Client.query(body));
// // 情境三:設定body參數,reqBodyType的值為formData
// java.util.Map<String, Object> formData = new java.util.HashMap<>();
// formData.put("param1", "value1");
// formData.put("param2", "value2");
// com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
// .setBody(formData);
// // 情境四:使用Stream參數傳遞檔案流
// com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
// .setStream("<FILE_STREAM>"); // <FILE_STREAM>需替換為實際的檔案流發起請求
通過com.aliyun.teaopenapi.Client調用callApi發起請求。同時,在請求過程中支援設定運行時參數,例如逾時配置、代理配置等,更多資訊請查看進階配置。
// 設定運行時選項
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// 忽略對 SSL 憑證的驗證
// runtime.ignoreSSL = true;
// 開啟自動重試機制
// runtime.autoretry = true;
// 設定自動重試次數
// runtime.maxAttempts = 3;
// 連線逾時
// runtime.connectTimeout = 5000;
// 讀取逾時
// runtime.readTimeout = 10000;
// 傳回值為Map類型,可從Map中獲得三類資料:body、headers、statusCode(HTTP返回的狀態代碼 )。
java.util.Map<String, ?> response = client.callApi(params, request, runtime);
System.out.println(new com.google.gson.Gson().toJson(response));程式碼範例
樣本:調用RPC風格的API
以調用ECS的DescribeInstanceTypeFamilies介面為例,展示如何使用泛化調用方式。
import com.aliyun.teaopenapi.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teaopenapi.models.OpenApiRequest;
import com.aliyun.teaopenapi.models.Params;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import static com.aliyun.openapiutil.Client.query;
public class Sample {
public static void main(String[] args) throws Exception {
Config config = new Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
.setEndpoint("ecs-cn-hangzhou.aliyuncs.com");
Client client = new Client(config);
Params params = new Params()
.setStyle("RPC") // API風格
.setVersion("2014-05-26") // API版本號碼
.setMethod("POST") // 要求方法
.setAction("DescribeInstanceTypeFamilies") // API名稱
.setPathname("/")
.setProtocol("HTTPS")
.setAuthType("AK")
.setReqBodyType("json")
.setBodyType("json");
// 設定查詢參數
Map<String, Object> queries = new HashMap<>();
queries.put("RegionId", "cn-hangzhou");
// 設定運行時選項
RuntimeOptions runtime = new RuntimeOptions();
OpenApiRequest request = new OpenApiRequest()
.setQuery(query(queries));
// 傳回值為Map類型,可從Map中獲得三類資料:body、headers、statusCode(HTTP返回的狀態代碼 )。
Map<String, ?> response = client.callApi(params, request, runtime);
System.out.println(new Gson().toJson(response));
}
}
樣本:調用RESTful(ROA)風格的API
以調用Container Service查詢叢集列表資訊為例,展示如何使用泛化調用。
import com.aliyun.teaopenapi.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teaopenapi.models.OpenApiRequest;
import com.aliyun.teaopenapi.models.Params;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import static com.aliyun.openapiutil.Client.query;
public class Test3 {
public static void main(String[] args_) throws Exception {
Config config = new Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
.setEndpoint("cs.cn-hangzhou.aliyuncs.com");
Client client = new Client(config);
Params params = new Params()
.setStyle("ROA") // API風格
.setVersion("2015-12-15") // API版本號碼
.setAction("DescribeClustersV1") // API名稱
.setPathname("/api/v1/clusters") // API資源路徑
.setMethod("GET") // 要求方法
.setProtocol("HTTPS")
.setAuthType("AK")
.setReqBodyType("json")
.setBodyType("json");
// 設定查詢參數
Map<String, Object> queries = new HashMap<>();
queries.put("name", "cluster-demo");
OpenApiRequest request = new OpenApiRequest()
.setQuery(query(queries));
RuntimeOptions runtime = new RuntimeOptions();
// 傳回值為 Map 類型,可從 Map 中獲得三類資料:響應體 body、回應標頭 headers、HTTP 返回的狀態代碼 statusCode。
Map<String, ?> response = client.callApi(params, request, runtime);
System.out.println(new Gson().toJson(response));
}
}