Reputation: 55
I'm making Xamarin.Forms app which should get JSON from api and then allow to display it. My code so far:
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;
}
Problem is that code don't even go to response.EnsureSuccessStatusCode(); so my list of objects is empty. On UWP version it's working without any problems. Here i'm gettin exception: System.Net.Http.HttpRequestException with message An error occurred while sending the request.
Upvotes: 4
Views: 7095
Reputation: 74194
SecureChannelFailure (The authentication or decryption has failed.)
or
System.Net.WebException: Error: TrustFailure
or
Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server.
By default, Xamarin.Android uses the older Mono Managed HttpClient handler that does not support TLS 1.2.
Open your Xamarin.Android
project settings, goto Build
/ Android Build
/ General
and use the AndroidClientHandler
.
This will add the following MSBuild properties directly to your .csproj
<AndroidHttpClientHandlerType>Xamarin.Android.Net.AndroidClientHandler</AndroidHttpClientHandlerType>
<AndroidTlsProvider>btls</AndroidTlsProvider>
Note: If doing this manually in the .csproj
, you need to add them to the debug AND release PropertyGroup.
Or programmatically set the HttpClient to use it:
client = new HttpClient(new AndroidClientHandler());
Note: You should be looking at the InnerException
for these types of errors
catch (Exception ex)
{
Console.WriteLine(@" Error {0}", ex.Message);
Console.WriteLine(@" Error {0}", ex.InnerException?.Message);
}
Upvotes: 7