发送https请求工具类

发送https请求的工具类,将默认的 TrustManager 和 HostnameVerifier 替换为不做任何校验的实现,这样就可以让 HttpURLConnection 在尝试建立安全连接时跳过所有验证,从而成功发送 HTTPS 请求。

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpUtils {

    static {
        try {
            // 创建 SSLContext 对象,并初始化 TrustManager 数组和 KeyManager 数组
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}

                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }}, new SecureRandom());

            // 将默认 SSLSocketFactory 替换为自定义的 SSLSocketFactory
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

            // 禁用 HostnameVerifier 验证主机名
            HttpsURLConnection.setDefaultHostnameVerifier((s, sslSession) -> true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送 GET 请求
     *
     * @param urlStr URL 地址
     * @return 响应字符串
     */
    public static String doGet(String urlStr) {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000); // 设置连接超时时间为 5 秒
            conn.setReadTimeout(5000); // 设置读取超时时间为 5 秒

            // 发送 GET 请求
            conn.connect();

            // 处理响应结果
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接和输入流
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result.toString();
    }

    /**
     * 发送 POST 请求
     *
     * @param urlStr  URL 地址
     * @param content 请求体内容
     * @return 响应字符串
     */
    public static String doPost(String urlStr, String content) {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000); // 设置连接超时时间为 5 秒
            conn.setReadTimeout(5000); // 设置读取超时时间为 5 秒

            // 发送 POST 请求
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(content.getBytes(StandardCharsets.UTF_8)); // 将请求体写入输出流
            os.flush();

            // 处理响应结果
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接和输入流
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result.toString();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值