尝试在Xamarin Android中调用HTTPS API,我正在接收接收异常(无法建立SSL连接,请参阅内部异常)

xam8gpfp  于 2023-04-18  发布在  Android
关注(0)|答案(2)|浏览(231)

我有一个移动的应用程序内置在Xamarin表单使用HTTP API的工作非常好,但当HTTP API的移动到HTTPS,我开始收到SSL异常
Project Properties Link
Android Properties Link
Exception Link
有没有可能的办法解决这个问题?

private HttpClient GetClient(HttpClientHandler handler = null)
{
    try
    {
        IProxyInfoProvider _proxyInfoProvider = DependencyService.Get<IProxyInfoProvider>();
        HttpClientHandler handlerClient = new HttpClientHandler()
        {
            Proxy = _proxyInfoProvider.GetProxySettings()
        };
        handlerClient.UseProxy = true;
        //ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        // handlerClient.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
        HttpClient client = new HttpClient(handlerClient
        return client;
    }
    catch (Exception ex)
    {
        throw;
    }
}

我无法使用服务点管理器或服务器证书自定义验证回调,因为该项目是PCL格式,目标是“.NET Framework 4.5”

hc8w905p

hc8w905p1#

尝试将Android SSL/TLS实施设置从“Managed TLS 1.0”更新为“Default(Native TLS 1.2+)”。这是根据documentation应该使用的设置。
2018年4月-由于安全要求的增加,包括PCI合规性,主要的云提供商和Web服务器预计将停止支持1.2以上的TLS版本。在Visual Studio的早期版本中创建的Xamarin项目默认使用旧版本的TLS。为了确保您的应用继续与这些服务器和服务一起使用,您应该使用如下所示的Android HttpClientNative TLS 1.2设置更新您的Xamarin项目,然后重新构建并重新部署您的应用程序给您的用户。

monwx1rj

monwx1rj2#

步骤1在Android项目中添加类

namespace Mobility.Droid.Dependency
{
    public class HttpClientHandlerCustomValidation : System.Net.Http.HttpClientHandler
    {
        public HttpClientHandlerCustomValidation() : base()
        {
            ServerCertificateCustomValidationCallback = ValidateServerCertficate;
        }
        static bool ValidateServerCertficate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }
}

第2步您将不得不编辑Android.csProj文件并编辑AndroidHttpClientHandlerType,为debug属性组和release属性组添加此标记。

<AndroidHttpClientHandlerType>Mobility.Droid.Dependency.HttpClientHandlerCustomValidation, Mobility.Droid</AndroidHttpClientHandlerType>

第3步你将不得不删除你生成的自定义客户端中的处理程序客户端

HttpClient client = new HttpClient()
        return client;

而不是

HttpClient client = new HttpClient(handlerClient)
        return client;

@brendanzagaeski来自this thread的评论帮助解决了这个问题

相关问题