AdSense

網頁

2021/11/7

Java 11 HttpClient發送請求範例

Java 11 使用HttpClient發送請求範例如下。


下面範例使用HttpClientHttpRequestHttpResponse發送請求取得股票日交易資訊

由於請求資源的protocal為https協議,也就是使用TSL/SSL通訊,所以要提供TSL憑證進行驗證,而這邊提供X509TrustManager的空實作方法來停用憑證驗證,否則可能會出現sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target錯誤。

Main.java

package com.abc.demo;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.Duration;

public class Main {

    public static void main(String[] args) throws Exception {

        // 建立HttpClient實例
        HttpClient httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1) // http 1.1
                .connectTimeout(Duration.ofSeconds(5)) // timeout after 5 seconds
                .sslContext(disabledSSLContext()) // disable SSL verify
                .build();

        // 臺灣證券交易所0056個股日成交資訊API
        String url = "https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json&date=20211105&stockNo=0056";

        // 建立HttpRequest請求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .build();

        // 發送請求並接收回應
        HttpResponse<String> response = httpClient.send(
                request, HttpResponse.BodyHandlers.ofString());

        // 取得回應主體內容
        String body = response.body();

        System.out.println(body);

    }

    private static SSLContext disabledSSLContext() throws KeyManagementException, NoSuchAlgorithmException {
        SSLContext sslContext = SSLContext.getInstance("TLS"); // https://docs.oracle.com/en/java/javase/11/docs/specs/security/standard-names.html#sslcontext-algorithms
        sslContext.init(
                null,
                new TrustManager[]{
                        new X509TrustManager() {
                            public X509Certificate[] getAcceptedIssuers() {
                                return null;
                            }

                            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                            }

                            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                            }
                        }
                },
                new SecureRandom()
        );
        return sslContext;
    }

}

請求取回的結果如下。

{"stat":"OK","date":"20211105","title":"110年11月 0056 元大高股息       各日成交資訊","fields":["日期","成交股數","成交金額","開盤價","最高價","最低價","收盤價","漲跌價差","成交筆數"],"data":[["110/11/01","21,338,625","673,437,956","31.54","31.65","31.49","31.56","+0.11","10,231"],["110/11/02","25,280,289","799,133,741","31.66","31.77","31.48","31.53","-0.03","15,992"],["110/11/03","14,294,336","453,304,212","31.55","31.77","31.55","31.77","+0.24","8,302"],["110/11/04","14,666,568","468,192,066","31.89","31.99","31.85","31.86","+0.09","9,298"],["110/11/05","16,911,957","538,747,208","31.90","31.95","31.71","31.95","+0.09","10,474"]],"notes":["符號說明:+/-/X表示漲/跌/不比價","當日統計資訊含一般、零股、盤後定價、鉅額交易,不含拍賣、標購。","ETF證券代號第六碼為K、M、S、C者,表示該ETF以外幣交易。"]}


沒有留言:

AdSense