且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Xamarin Android 问题通过 HTTPS 连接到使用自签名证书的站点:“未找到证书路径的信任锚".

更新时间:2021-09-07 21:48:06

我能够让它在 Android 和 iOS 中都能运行.

I was able to get this to work in both Android and iOS.

iOS 很简单,只需覆盖 ServicePointManager.ServerCertificateValidationCallback:

iOS was easy, just override ServicePointManager.ServerCertificateValidationCallback:

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

对于 Android 我使用了Bruno Caceiro 对类似问题的回答 和创建的依赖服务.

For Android I used Bruno Caceiro's answer from a similar question and a created Dependency Service.

在我的 Xamarin Forms 项目中,我添加了一个简单的界面:

In my Xamarin Forms project I added a simple interface:

public interface IHTTPClientHandlerCreationService
{
  HttpClientHandler GetInsecureHandler();
}

在我的 Xamarin Android 项目中,我实现了接口:

And in my Xamarin Android project I implemented the interface:

[assembly: Dependency(typeof(HTTPClientHandlerCreationService_Android))]
namespace MyApp.Droid
{
  public class HTTPClientHandlerCreationService_Android : CollateralUploader.Services.IHTTPClientHandlerCreationService
  {
    public HttpClientHandler GetInsecureHandler()
    {
      return new IgnoreSSLClientHandler();
    }
  }

  internal class IgnoreSSLClientHandler : AndroidClientHandler
  {
    protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
    {
      return SSLCertificateSocketFactory.GetInsecure(1000, null);
    }

    protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
    {
      return new IgnoreSSLHostnameVerifier();
    }
  }

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

共享代码以正确设置 HttpClient:

Shared code to correctly set up the HttpClient:

switch (Device.RuntimePlatform)
{
  case Device.Android:
    this.httpClient = new HttpClient(DependencyService.Get<Services.IHTTPClientHandlerCreationService>().GetInsecureHandler());
    break;
  default:
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
    this.httpClient = new HttpClient(new HttpClientHandler());
    break;
}