Skip to content Skip to sidebar Skip to footer

Xamarin: Java.security.cert.certpathvalidatorexception: Trust Anchor For Certification Path Not Found

In Xamarin. I've been trying to make communications between my Web API and my Xamarin project. Here's the code for my controller: // GET api/values public List G

Solution 1:

//Use this, it worked for me. HttpClient client;

publicclassdatastore {
   var httpClientHandler = newHttpClientHandler();
            
   httpClientHandler.ServerCertificateCustomValidationCallback = 
   (message, cert, chain, errors) => { returntrue; };

   client = newHttpClient(httpClientHandler);
}

//... use the client to make request. it will bypass //the ssl certificates verification. 

Solution 2:

For Android you should do something more .

in Forms ,create an interface

publicinterfaceIHTTPClientHandlerCreationService
{
  HttpClientHandler GetInsecureHandler();
}

in Android implemented the interface:

[assembly: Dependency(typeof(HTTPClientHandlerCreationService_Android))]
namespacexxx.Droid
{
  publicclassHTTPClientHandlerCreationService_Android : CollateralUploader.Services.IHTTPClientHandlerCreationService
  {
    public HttpClientHandler GetInsecureHandler()
    {
      returnnew IgnoreSSLClientHandler();
    }
  }

  internalclassIgnoreSSLClientHandler : AndroidClientHandler
  {
    protectedoverride SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
    {
      return SSLCertificateSocketFactory.GetInsecure(1000, null);
    }

    protectedoverride IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
    {
      returnnew IgnoreSSLHostnameVerifier();
    }
  }

  internalclassIgnoreSSLHostnameVerifier : Java.Lang.Object, IHostnameVerifier
  {
    publicboolVerify(string hostname, ISSLSession session)
    {
      returntrue;
    }
  }
}

And when you call the method Get

publicasyncvoidBindToListView()
{
  HttpClient client;

  switch (Device.RuntimePlatform)
  {
    case Device.Android:
      this.httpClient = new HttpClient(DependencyService.Get<Services.IHTTPClientHandlerCreationService>().GetInsecureHandler());
      break;
    default:
      ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
      this.httpClient = new HttpClient(new HttpClientHandler());
      break;
  }

  var response = await client.GetStringAsync("https://10.0.2.2:#####/api/Values");
  var posts = JsonConvert.DeserializeObject<ObservableCollection<Posts>>(response);
  lv.ItemsSource = posts;
}

In addition, I suggest that you can use ObservableCollection instead of List because it has implemented the interface INotifyPropertyChanged . Otherwise the UI will never been updated .

Post a Comment for "Xamarin: Java.security.cert.certpathvalidatorexception: Trust Anchor For Certification Path Not Found"