Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebException in Xamarin, using HttpClient

I'm learning how to use xamarin with C#, and I've got an android app to make web requests to an external API and I'm receiving the following error;

System.Net.Http.HttpRequestException: An error occurred while sending the 
request ---> System.Net.WebException: Error: SecureChannelFailure (The   
authentication or decryption has failed.) ---> System.IO.IOException: The 
authentication or decryption has failed. ---> System.IO.IOException: The 
authentication or decryption has failed. ---> 
Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed.

My code is as following;

public async Task<List<T>> GetList<T>(string url)
    {
        HttpClient client = new HttpClient();
        var response = await client.GetAsync(new Uri(url));
        response.EnsureSuccessStatusCode();
        var content = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<List<T>>(content);
    }

The MainClass in android calls the core class, which calls this service class.

HttpClient requests work when the API does not use HTTPS, but throws this error whenever I use an API that has HTTPS enabled.

I'm also using a Portable Class Library to store code, so using HttpWebRequest for web requests isn't possible.

I have also tried;

ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;

And;

System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();

In my application OnCreate class (android).

I have also changed the HttpClient implementation to AndroidClientHandler, along with changing the SSL/TLS implementation to 1.1. Along with attempting this on an emulator and a device.

Does anyone have any advice?

like image 241
Tom Johnson Avatar asked Jan 25 '17 12:01

Tom Johnson


1 Answers

Try this: Open Android project property -> Android Options -> Advanced

Switch the HttpClient implementation setting from Default to Android

It seems that the default Mono client handler is broken for HTTPS.

like image 51
Yanbin Hu Avatar answered Oct 20 '22 00:10

Yanbin Hu