【GET方式调用https,工具类】

package com.wbr.demo;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.X509Certificate;

public class HttpsUtils {
    public static void main(String[] args) throws Exception {
        // 请求的URL地址
        String codeUrl = "https://cx.mem.gov.cn/prod-api/certsearch/code";
        // 发送GET请求并获取响应结果
        String result = HttpsUtils.httpGet(codeUrl);
        // 输出响应结果
        System.out.println(result);
    }

    /**
     * 发送HTTPS GET请求
     *
     * @param httpUrl 请求的URL地址
     * @return 响应结果
     * @throws Exception
     */
    public static String httpGet(String httpUrl) throws Exception {
        // 创建信任管理器,用于信任所有证书
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

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

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

        // 获取默认的SSL上下文
        SSLContext sslContext = SSLContext.getInstance("TLS");
        // 初始化SSL上下文,传入信任管理器
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // 设置默认的SSL套接字工厂
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

        // 创建URL对象
        URL url = new URL(httpUrl);

        // 打开HTTPS连接
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // 设置请求方法为GET
        connection.setRequestMethod("GET");

        // 获取响应状态码
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // 读取响应内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 关闭连接
        connection.disconnect();
        // 返回响应结果
        return response.toString();
    }
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值