API网关 APIG-Java:调用API示例

时间:2024-04-19 17:29:45

调用API示例

  1. 把API信息替换到HttpClientDemo.java中对应位置。

    HttpClientDemo中引用以下类,可在“获取SDK”包中的“src”文件下查看:

    • Constant:demo中用到的常量。
    • SSLCipherSuiteUtil:tls认证配置参数的工具类,比如配置客户端不校验证书。
    • UnsupportProtocolException:异常处理类。
    public class HttpClientDemo {
        private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientDemo.class);
        public static void main(String[] args) throws Exception {
            // Create a new request.
            Request httpClientRequest = new Request();
            try {
                // Set the request parameters.
                // AppKey, AppSecrect, Method and Url are required parameters.
                // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables.
                // In this example, the AK/SK are stored in environment variables for identity authentication. 
                // Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
                httpClientRequest.setKey(System.getenv("HUAWEICLOUD_SDK_AK"));
                httpClientRequest.setSecret(System.getenv("HUAWEICLOUD_SDK_SK"));
                httpClientRequest.setMethod("POST");
                // Set a request URL in the format of https://{Endpoint}/{URI}.
                httpClientRequest.setUrl("put your request url here");
                httpClientRequest.addHeader("Content-Type", "text/plain");
                // Set a body for http request.
                httpClientRequest.setBody("put your request body here");
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                return;
            }
            CloseableHttpClient client = null;
            try {
                // Sign the request.
                HttpRequestBase signedRequest = Client.sign(httpClientRequest, Constant.SIGNATURE_ALGORITHM_SDK_HMAC_SHA256);
                if (Constant.DO_VERIFY) {
                    // creat httpClient and verify ssl certificate
                    HostName.setUrlHostName(httpClientRequest.getHost());
                    client = (CloseableHttpClient) SSLCipherSuiteUtil.createHttpClientWithVerify(Constant.INTERNATIONAL_PROTOCOL);
                } else {
                    // creat httpClient and do not verify ssl certificate
                    client = (CloseableHttpClient) SSLCipherSuiteUtil.createHttpClient(Constant.INTERNATIONAL_PROTOCOL);
                }
                HttpResponse response = client.execute(signedRequest);
                // Print the body of the response.
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    LOGGER.info("Processing Body with name: {} and value: {}", System.getProperty("line.separator"),
                            EntityUtils.toString(resEntity, "UTF-8"));
                }
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
            } finally {
                if (client != null) {
                    client.close();
                }
            }
        }
    }

  2. 运行HttpClientDemo.java,对请求进行签名、访问API并打印结果。

    示例结果如下:

    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Print the authorization: [Authorization: SDK-HMAC-SHA256 Access=3afe0280a6e1466e9cb6f23bcccdba29, SignedHeaders=host;x-sdk-date, Signature=26b2abfa40a4acf3c38b286cb6cbd9f07c2c22d1285bf0d4f6cf1f02d3bfdbf6]
    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Print the status line of the response: HTTP/1.1 200 OK
    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Date and value: Fri, 26 Aug 2022 08:58:51 GMT
    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Content-Type and value: application/json
    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Transfer-Encoding and value: chunked
    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Connection and value: keep-alive
    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: Server and value: api-gateway
    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Header with name: X-Request-Id and value: 10955c5346b9512d23f3fd4c1bf2d181
    [main] INFO com.huawei.apig.sdk.demo.HttpClientDemo - Processing Body with name: 
     and value: {"200": "sdk success"}

    显示{"200": "sdk success"},表示签名成功,API成功请求到后端。

    如果改变AK或SK的值,API网关将返回的错误信息error_msg。

support.huaweicloud.com/devg-apig/apig-dev-180307002.html