package com.ruoyi.project;
import okhttp3.*;
import javax.net.ssl.*;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
public class Main2 {

    private static OkHttpClient client = null;

    public Main2() {
        // 创建信任所有证书的 OkHttpClient
        this.client = createUnsafeOkHttpClient();
    }

    public static void main(String[] args) {
        String url = "http://www.chifeng.gov.cn/zwgk/xxgkzl/zfxxgknb/2024zfxxgknb/szf_750/202503/t20250306_2545851.html";
        String url1 = "https://www.tongliao.gov.cn/xwzx/mrtt/202504/t20250401_934030.html";
        final boolean brokenLink = isBrokenLink(url);
        System.out.println(brokenLink);
    }
    /**
     * 检查链接是否失效（404 或 HTTP 错误码 >= 400）
     */
    public static boolean isBrokenLink(String url) {
        Request request = new Request.Builder()
                .url(url)
                .head() // 使用 HEAD 方法，只请求头部信息
                .build();
        client = createUnsafeOkHttpClient();

        try (Response response = client.newCall(request).execute()) {
            int responseCode = response.code();
            return responseCode == 404 || responseCode >= 400;
        } catch (Exception e) {
            return false; // 请求失败视为失效链接
        }
    }

    /**
     * 创建一个信任所有 HTTPS 证书的 OkHttpClient（仅用于测试环境！）
     */
    private static OkHttpClient createUnsafeOkHttpClient() {
        try {
            // 创建信任所有证书的 TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };

            // 配置 SSLContext 信任所有证书
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // 创建 OkHttpClient.Builder 并设置自定义 SSLSocketFactory 和 HostnameVerifier
            return new OkHttpClient.Builder()
                    .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true) // 信任所有主机名
                    .connectTimeout(60, TimeUnit.SECONDS) // 连接超时 60s
                    .readTimeout(60, TimeUnit.SECONDS)     // 读取超时 60s
                    .followRedirects(true)                // 跟随重定向
                    .build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create unsafe OkHttpClient", e);
        }
    }
}
