BÀI 71 - BỎ QUA LỖI TRANG WEB THIẾU CHỨNG CHỈ SSL TRONG ANDROID

  • Cái mình test rồi hệ thống đã bỏ qua lỗi nhưng nó vẫn chưa đọc được nội dung trang web nên các bạn có thể tìm hiểu thêm là vì sao nhá.

  • Giải pháp của mình là copy nội dung cần lấy nội dung của trang web sau đó ném lên hosting (hay trang web) của mình. Firebase có cung cấp cho các bạn tạo hosting free á. Mình làm được rồi và có hướng dẫn trong loạt bài lập trình web. Nhưng đây là cách hơi tù. Nếu nội dung thay đổi thường xuyên thì bạn cũng phải cập nhật thường xuyên bằng "cơm" nhá.

  • Tạo java class có tên HttpsTrustManager

import java.security.KeyManagementException;

import java.security.NoSuchAlgorithmException;

import java.security.SecureRandom;

import java.security.cert.X509Certificate;


import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSession;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;


public class HttpsTrustManager implements X509TrustManager {


private static TrustManager[] trustManagers;

private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};


@Override

public void checkClientTrusted(

java.security.cert.X509Certificate[] x509Certificates, String s)

throws java.security.cert.CertificateException {

}


@Override

public void checkServerTrusted(

java.security.cert.X509Certificate[] x509Certificates, String s)

throws java.security.cert.CertificateException {

}


public boolean isClientTrusted(X509Certificate[] chain) {

return true;

}


public boolean isServerTrusted(X509Certificate[] chain) {

return true;

}


@Override

public X509Certificate[] getAcceptedIssuers() {

return _AcceptedIssuers;

}


public static void allowAllSSL() {

HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {


@Override

public boolean verify(String arg0, SSLSession arg1) {

return true;

}


});


SSLContext context = null;

if (trustManagers == null) {

trustManagers = new TrustManager[]{new HttpsTrustManager()};

}


try {

context = SSLContext.getInstance("TLS");

context.init(null, trustManagers, new SecureRandom());

} catch (NoSuchAlgorithmException | KeyManagementException e) {

e.printStackTrace();

}


HttpsURLConnection.setDefaultSSLSocketFactory(context

.getSocketFactory());

}

}

  • Để sử dụng, trước đoạn code đọc nội dung trang web nào đó, bạn gọi phương thức này. Bài 70 có ví dụ sử dụng cái này rồi đó.

HttpsTrustManager.allowAllSSL();