Xamarin Android HttpClient Error when use from a Class

旧时模样 提交于 2019-12-12 03:05:39

问题


I have the following code that errors out when going to site what has SSL. (Error: SecureChannelFailure (The authentication or decryption has failed.) Their SSL cert is valid. When the HttpClient code is called directly there is not issue. What is wrong with my code?

 Uri uri =new Uri("https://jsonplaceholder.typicode.com/posts/1");
  using (HttpClient httpclient = new HttpClientClass())
   {
       var tt = await httpclient.GetAsync(uri);
       string tx = await tt.Content.ReadAsStringAsync();
       Log.Info(TAG, tx);
    }




 public class HttpClientClass : HttpClient
  {
     private HttpClient _httpclient = null;
     private HttpClientHandler messagehandler = new Xamarin.Android.Net.AndroidClientHandler();

     public  HttpClientClass()
     {
       _httpclient = new HttpClient(messagehandler);
      }
   }

Code with No Problem

Uri uri =new Uri("https://jsonplaceholder.typicode.com/posts/1");
  using (HttpClient httpclient = new HttpClient())
   {
       var tt = await httpclient.GetAsync(uri);
       string tx = await tt.Content.ReadAsStringAsync();
       Log.Info(TAG, tx);
    }

回答1:


Thanks to Https with TLS 1.2 in Xamarin here is the solution. Add Nuget modernhttpclient by Paul Betts and use below. That should work within class or not.

            Uri uri = new Uri("https://jsonplaceholder.typicode.com/posts/1");
            using (var httpClient = new HttpClient(new NativeMessageHandler()))
            {
                var tt = await httpClient.GetAsync(uri);
                string tx = await tt.Content.ReadAsStringAsync();
                //Log.Info(TAG, tx);
            }


来源:https://stackoverflow.com/questions/40445255/xamarin-android-httpclient-error-when-use-from-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!