Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 89864

Correct instantiation of HttpClient XamarinForms(Android)

$
0
0

Hi Folks,

I have a Xamarin.Forms project which strongly builds on networking: fetching and sending JSON data from/to a WebAPI and displaying images hosted on the WebAPI server.

The quality of current network interactions between mobile App and remote WebAPI server are extremely bad even for the Http-JSON data transfer part. The image downloading and display part will be the focus of another question.

I already know, that Xamarin.Forms(Android) needs platform specific settings to use the native HttpClient implementation which should be used as default instead of the managed HttpClient implementation. I already have that settings in place.

Now the question:
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:

´´´´
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;
});

    private HttpClient HttpClient => httpClient.Value;

´´´´


Viewing all articles
Browse latest Browse all 89864

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>