釋放 AI 的強大力量

100 萬免費代幣

88% 價格優惠

立即啟用
本文由簡體中文內容自動轉碼而成。阿里雲不保證此自動轉碼的準確性、完整性及時效性。本文内容請以簡體中文版本為準。

泛化調用

更新時間:2025-03-04 19:21

阿里雲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.6</version>
</dependency>

調用OpenAPI

初始化請求用戶端

通過建立com.aliyun.teaopenapi.Client對象初始化請求用戶端,並通過該Client發起OpenAPI調用。在初始化用戶端時,也支援使用Credentials工具,關於Credentials工具的更多資訊,請參見管理訪問憑據

說明

請求用戶端對象無需手動銷毀,會自動被記憶體回收機制回收。

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                .setEndpoint("ecs.cn-hangzhou.aliyuncs.com"); // Endpoint為您調用的OpenAPI支援的服務存取點
        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版本、請求方式等資訊。

        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("DescribeRegions")  // 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)傳遞。

請求參數傳遞方式

描述

query

通過查詢參數傳遞參數。

說明

如果RPC介面的請求參數採用query傳參方式,則該請求參數同樣支援使用body進行傳遞。

body

通過請求體(body)傳遞參數。在使用請求體(body)傳遞參數時,需要根據請求體的類型設定reqBodyType的值。

        // 方式一:設定查詢參數(query)
        java.util.Map<String, Object> queries = new java.util.HashMap<>();
        queries.put("InstanceChargeType", "PrePaid");
        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("InstanceChargeType", "PrePaid");
//        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
//                .setBody(com.aliyun.openapiutil.Client.query(body));

//        // 方式三:設定body參數,reqBodyType的值為byte
//        java.util.Map<String, Object> body = new java.util.HashMap<>();
//        body.put("InstanceChargeType", "PrePaid");
//        com.google.gson.Gson gson = (new com.google.gson.GsonBuilder()).disableHtmlEscaping().create();
//        byte[] bytes = gson.toJson(body).getBytes(java.nio.charset.StandardCharsets.UTF_8);
//        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
//                .setBody(bytes);

//        // 方式四:設定body參數,reqBodyType的值為formData
//        java.util.Map<String, Object> body = new java.util.HashMap<>();
//        body.put("InstanceChargeType", "PrePaid");
//        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
//                .setBody(body);

發起請求

通過com.aliyun.teaopenapi.Client調用callApi發起請求。

        // 設定運行時選項
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        // 傳回值為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的DescribeRegions介面為例,展示如何使用泛化調用方式。

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("DescribeRegions")  // API名稱
                .setPathname("/") 
                .setProtocol("HTTPS")
                .setAuthType("AK")
                .setReqBodyType("json")
                .setBodyType("json");
        // 設定查詢參數
        Map<String, Object> queries = new HashMap<>();
        queries.put("InstanceChargeType", "PrePaid");
        // 設定運行時選項
        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-qingdao.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));
    }
}
  • 本頁導讀 (1, M)
  • 特點
  • 使用說明
  • 安裝核心SDK
  • 調用OpenAPI
  • 初始化請求用戶端
  • 配置OpenAPI資訊
  • 配置請求參數
  • 發起請求
  • 程式碼範例
  • 樣本:調用RPC風格的API
  • 樣本:調用RESTful(ROA)風格的API
文檔反饋
phone 聯絡我們

立即和Alibaba Cloud在線服務人員進行交談,獲取您想了解的產品信息以及最新折扣。

alicare alicarealicarealicare