SSL证书与发起https请求获取结果

本文介绍了一种通过自定义X509TrustManager实现对HTTPS请求的信任管理方式,并提供了GET和POST请求的具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class TEX509TrustManager implements X509TrustManager { 

//证书路径
private final static String TrustedCertsPath = "*:\\***\\***"; 
//密码
private final static String PassWord = "***";

    private static X509TrustManager sunJSSEX509TrustManager = null; 
    
    TEX509TrustManager() throws Exception { 
    if(null==sunJSSEX509TrustManager) {
        KeyStore ks = KeyStore.getInstance("JKS"); 
        ks.load(new FileInputStream(TrustedCertsPath),PassWord.toCharArray()); 
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE"); 
        tmf.init(ks); 
        TrustManager tms [] = tmf.getTrustManagers(); 
        for (int i = 0; i < tms.length; i++) { 
            if (tms[i] instanceof X509TrustManager) { 
                sunJSSEX509TrustManager = (X509TrustManager) tms[i]; 
                return; 
            } 
        } 
    }else {
    return;
    }
        throw new Exception("Couldn't initialize"); 
    } 


    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
        try { 
            sunJSSEX509TrustManager.checkClientTrusted(chain, authType); 
        } catch (CertificateException excep) { 


        } 
    } 


    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
        try { 
            sunJSSEX509TrustManager.checkServerTrusted(chain, authType); 
        } catch (CertificateException excep) { 


        } 
    } 


    public X509Certificate[] getAcceptedIssuers() { 
        return sunJSSEX509TrustManager.getAcceptedIssuers(); 
    } 


发起https请求并获取结果

Get请求

public static String httpsGetRequest(String requestUrl){  
    StringBuffer buffer=null;  
    try{  
    //创建SSLContext  
    SSLContext sslContext=SSLContext.getInstance("SSL");  
    TrustManager[] tm={new TEX509TrustManager()};  
    //初始化  
    sslContext.init(null, tm, new java.security.SecureRandom());;  
    //获取SSLSocketFactory对象  
    SSLSocketFactory ssf=sslContext.getSocketFactory();  
    URL url=new URL(requestUrl);  
    HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();  
    conn.setDoInput(true);  
    conn.setUseCaches(false);  
    //设置当前实例使用的SSLSoctetFactory  
    conn.setSSLSocketFactory(ssf);  
    conn.connect();  
    //读取服务器端返回的内容  
    InputStream is=conn.getInputStream();  
    InputStreamReader isr=new InputStreamReader(is,"utf-8");  
    BufferedReader br=new BufferedReader(isr);  
    buffer=new StringBuffer();  
    String line=null;  
    while((line=br.readLine())!=null){  
        buffer.append(line);  
    }  
    }catch(Exception e){  
        e.printStackTrace();  
    }  
    return buffer.toString();  
}


post请求 参数(xmlObj)转化为xml格式并请求


public static String httpsPostRequest(String url,Object xmlObj,String charset) throws Exception {
SSLContext sc = SSLContext.getInstance("SSL");  
        sc.init(null, new TrustManager[]{new TEX509TrustManager()},new java.security.SecureRandom());  
        URL console = new URL(url);  
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();  
        conn.setSSLSocketFactory(sc.getSocketFactory());  
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());  
        conn.setDoOutput(true);  
        conn.connect();  
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());  
        //查看charset编码格式是否为空
        if(CommonTools.isNullOfString(charset)) {
        charset = "utf-8";
        }
        XStream xStreamForRequestPostData = new XStream(new DomDriver(charset, new XmlFriendlyNameCoder("-_", "_")));
        xStreamForRequestPostData.alias("xml", xmlObj.getClass());
        //将要提交给API的数据对象转换成XML格式数据Post给API
        String postDataXML = xStreamForRequestPostData.toXML(xmlObj);
        out.write(postDataXML.getBytes(charset));  
        // 刷新、关闭  
        out.flush();  
        out.close();  
        InputStream is = conn.getInputStream();  
        if (is != null) {  
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
            byte[] buffer = new byte[1024];  
            int len = 0;  
            while ((len = is.read(buffer)) != -1) {  
                outStream.write(buffer, 0, len);  
            }  
            is.close();  
            return outStream.toString();  
        }  
        return null;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值