HttpsURLConnection使用,並實現雙向認證

添加信任全部服務端證書也可在方法中控制java

package something;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;
/**
 * 信任全部證書
 * @author hp
 *
 */
public class AllTrustManager implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        // TODO Auto-generated method stub

    }

    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        // TODO Auto-generated method stub

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }

}

使用HttpsURLConnection發送POST請求(默認443端口)app

package something;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

public class HttpsRequest {
    //測試url
    private final static String URL_TEST="https://www.baidu.com";
    //客戶端證書路徑
    private final static String PATH="c://xxxx";
    //證書密碼
    private final static String psw="123456";
    /**
     * 發送POST請求
     * @param agrs
     * @return
     * @throws IOException
     * @throws KeyManagementException
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws CertificateException
     * @throws UnrecoverableKeyException
     */
    public String doPost(String agrs) throws IOException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException{
        //導入客戶端證書
        KeyStore ks=KeyStore.getInstance("pkcs12");
        FileInputStream instream = new FileInputStream(new File(PATH));
        ks.load(instream, psw.toCharArray());
        KeyManagerFactory kmf=KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, psw.toCharArray());
        //添加信任證書
        TrustManager[] tm={new AllTrustManager()};//AllTrustManager()爲信任全部證書
        
        SSLContext ctx=SSLContext.getInstance("SSL");//建立ssl上下文
        //初始化 ;參數1爲null,則不上傳客戶端證書(一般狀況都是如此);
        ctx.init(kmf.getKeyManagers(), tm, new SecureRandom());
        //ctx.init(kmf.getKeyManagers(), null, new SecureRandom());//驗證系統默認證書
        //ctx.init(kmf.getKeyManagers(), TrustManager[] tm, new SecureRandom());//導出服務端證書,而後按照keymanager同樣實現trustmanager
        SSLSocketFactory sf=ctx.getSocketFactory();
        
        URL _url=new URL(URL_TEST);
        HttpsURLConnection conn=(HttpsURLConnection) _url.openConnection();
        conn.setRequestMethod("POST");//設定請求方法
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(20000);
        conn.setDoInput(true);//打開輸入流
        conn.setDoOutput(true);//打開輸出流寫入寫出參數必需
        conn.setSSLSocketFactory(sf);//添加ssl參數
        //輸出參數
        PrintWriter pw=new PrintWriter(conn.getOutputStream());
        pw.write(agrs);
        pw.flush();
        //獲取輸入流
        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer result=new StringBuffer();
        String s=br.readLine();
        while(s!=null){
            result.append(s);
            s=br.readLine();
        }
        pw.close();
        br.close();
        return result.toString();
    }
}
相關文章
相關標籤/搜索