J4ni
J4ni

Reputation: 217

Forms(Android: )How to correctly instantiate native HttpClient to use in shared project

I don't know hot to correctly instantiate the native Android HttpClient for my shared Xamarin.Forms project. I have done reading and searching.

The questions: 1. How do I make sure, that my Android client will use the native HttpClient for all kinds of network transfer even for actions defined in the shared code? 2. Do I have to instantiate a HttpClient in the Project.Android project part of the code and inject the object into the Project.App() constructor like Project.App(HttpClient httpClient) or does that function automatically by some kind of build-time magic? 3. Currently my code would be fine with a HttpClient built by its default Constructor, but can I have constructor parameters when instantiating native HttpClient?

Current code snipets and settings: - Scope: Xamarin.Forms Android - architectures: armeaby-v7a;arm64-v8a (have x86 in separate configuration, that works much better) - HttpClient implementation: Android - SSL/TLS implementation: Default (Native TLS 1.2+) - Xamarin.Forms 4.1.0.581479 - SDK: NETStandard 2.0.3

Project.Android MainActivity.cs:

using Android.App;
using Android.Content.PM;
using Android.OS;

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);            
        LoadApplication(new App());
    }
}


My HttpClient instantiation in the shared project: basically creates the object with default constructor when first needed and reuses it for every operation

private static Lazy httpClient = new Lazy(
() =>
{
var client = new HttpClient();
return client;
});

Upvotes: 0

Views: 245

Answers (1)

Akshar M.
Akshar M.

Reputation: 146

The ultimate purpose of Android - SSL/TLS implementation to improve performance so i whould like to suggest you use NuGet package modernhttpclient. Replace below line in your code

   private static Lazy httpClient = new Lazy(() =>
     {   
      var client = new HttpClient(new NativeMessageHandler());
      return client;
     });

using NativeMessageHandler you can handle both Android and iOS,

Hope this will help you.

Upvotes: 1

Related Questions