Android HttpURLConnection 繞過證書訪問Https網址

針對訪問Https網站,必須具有認可的證書,經過驗證後才能訪問該網站。

通常需要機構所發行的證書,但在開發階段還未申請到核可的證書時,我們可透過繞過證書的方式,來訪問Https網站。

要繞過證書的方式,主要是重寫HostnameVerifier的驗證方式及配合X509TrustManager來處理授權。

Step 1: 建立class : CustomHostnameVerifier

首先,先在文件中建立CustomHostnameVerifier, 並複寫HostnameVerifier的驗證方法,通過所有的驗證。

Connection.java
1
2
3
4
5
6
private class CustomHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}

Step 2: 建立class : CustomTrustManager

建立CustomTrustManager來處理授權。

Connection.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private class CustomTrustManager implements X509TrustManager {

public CustomTrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
super();
}

@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

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

Step 3: 設定SSL及建立連線

在建立HttpURLConnection連線之前,我們必須先設定好SSL相關設定。

Connection.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new CustomTrustManager(null) }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new CustomHostnameVerifier());

URL url = new URL(api);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setUseCaches(true);
httpConn.setAllowUserInteraction(true);

httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setConnectTimeout(3000);
httpConn.setReadTimeout(3000);
...

這樣就能夠繞過證書,達到免簽的方式訪問Https的網站了。

Android HttpURLConnection 繞過證書訪問Https網址

https://nickcarter9.github.io/2019/12/10/2019/2019_12_10-httpurlconnection_ssl/

作者

Nick Lin

發表於

2019-12-10

更新於

2023-01-18

許可協議


評論