HttpClient not working on android

Chr*_*isB 4 c# xamarin.android xamarin xamarin.forms

我正在制作 Xamarin.Forms 应用程序,它应该从 api 获取 JSON,然后允许显示它。到目前为止我的代码:

    public async void jsonDownload()
    {
        connect();
        await downloadData();


    }
    public void connect()
    {
        client = new HttpClient();
        client.MaxResponseContentBufferSize = 256000;
    }
    public async Task<List<Jsonclass>> downloadData()
    {

        String url = "https://my-json-server.typicode.com/kgbzoma/TestJsonFile/all";
        var uri = new Uri(string.Format(url, string.Empty));
        try
        {

            var response = await client.GetAsync(uri).ConfigureAwait(false);
            response.EnsureSuccessStatusCode(); //NEVER GET HERE

            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); 
            List = JsonConvert.DeserializeObject<List<Jsonclass>>(content);

        }catch (Exception ex)
        {
            Debug.WriteLine(@"     Error {0}", ex.Message);
        }
        return List;
    }
Run Code Online (Sandbox Code Playgroud)

问题是代码甚至不去 response.EnsureSuccessStatusCode(); 所以我的对象列表是空的。在 UWP 版本上,它可以正常工作。这里我刚开始出现异常:System.Net.Http.HttpRequestException 带有消息发送请求时发生错误。

Sus*_*ver 5

SecureChannelFailure(身份验证或解密失败。)

或者

System.Net.WebException: 错误: TrustFailure

或者

Mono.Security.Protocol.Tls.TlsException:从服务器收到的证书无效。

通过默认情况下,Xamarin.Android使用旧的单管HttpClient的处理器不支持TLS 1.2。

打开你的Xamarin.Android项目设置,转到Build/ Android Build/General和使用AndroidClientHandler

在此处输入图片说明

这会将以下 MSBuild 属性直接添加到您的 .csproj

<AndroidHttpClientHandlerType>Xamarin.Android.Net.AndroidClientHandler</AndroidHttpClientHandlerType>
<AndroidTlsProvider>btls</AndroidTlsProvider>
Run Code Online (Sandbox Code Playgroud)

注意:如果在 中手动执行此操作,则.csproj需要将它们添加到调试和发布 PropertyGroup。

或者以编程方式设置 HttpClient 以使用它:

client = new HttpClient(new AndroidClientHandler());
Run Code Online (Sandbox Code Playgroud)

注意:您应该查看InnerException这些类型的错误

catch (Exception ex)
{
    Console.WriteLine(@"     Error {0}", ex.Message);
    Console.WriteLine(@"     Error {0}", ex.InnerException?.Message);
}
Run Code Online (Sandbox Code Playgroud)