我正在制作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;
}
问题在于代码甚至没有响应。EnsureSuccessStatusCode(); 因此我的对象列表为空。在UWP版本上,它可以正常工作。这是我的异常:带有消息的System.Net.Http.HttpRequestException发送请求时发生错误。
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>
注意:如果在中手动进行操作,则.csproj
需要将它们添加到调试并释放PropertyGroup。
或以编程方式将HttpClient设置为使用它:
client = new HttpClient(new AndroidClientHandler());
注意:您应该查看InnerException
这些类型的错误
catch (Exception ex)
{
Console.WriteLine(@" Error {0}", ex.Message);
Console.WriteLine(@" Error {0}", ex.InnerException?.Message);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句