在Xamarin.android中,忽略SSL证书校验

在Xamarin.android中,如果遇到SSL证书无效或者是自签名的,可能会导致请求失败。类似下面的错误:

解决方法,就是在 android 这边忽略 ssl 证书检查。

在 Activity 的 OnCreate方法里面 加入  IgnoreSSLX509Certificate(); 方法。

private void IgnoreSSLX509Certificate()
{
    ITrustManager tm = new CustomX509TrustManager();
    SSLContext sc = SSLContext.GetInstance("SSL");
    sc.Init(null, new ITrustManager[] { tm }, new SecureRandom());
    HttpsURLConnection.DefaultSSLSocketFactory = sc.SocketFactory;
    HttpsURLConnection.DefaultHostnameVerifier = new CustomHostnameVerifier();
}

public class CustomHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
    public bool Verify(string hostname, ISSLSession session)
    {
        return true;
    }
}

public class CustomX509TrustManager : Java.Lang.Object, IX509TrustManager
{
    public void CheckClientTrusted(X509Certificate[] chain, string authType)
    {
    }

    public void CheckServerTrusted(X509Certificate[] chain, string authType)
    {
    }

    public X509Certificate[] GetAcceptedIssuers()
    {
        return new X509Certificate[0];
    }
}