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

Best way to use HttpClient, as singleton or new instance for each http request?

$
0
0

Hello everyone,

what is the best practice to use HttpClient?
Is it better use it as singleton or as a new instance for each request?

I'd tried to use it as singleton and it works nice, but when I make two 2 different and consecutive requests (I mean 2 request versus 2 different services paths) the second one return "bad request 400". The problem disappears when I use a breakpoint in Xamarin Studio for few seconds.

Does HttpClient store some value into the Header or something else?

In the code below there is the singleton initialization:

`

        client = new HttpClient (clientHandler);
        //client.Timeout = new TimeSpan(20000);     
        client.BaseAddress = new Uri(ServicesPath.BASE_URL);

        var usernamePassword ="foo" + ":" + "bar";
        var bytes = Encoding.UTF8.GetBytes(usernamePassword);
        var auth = Convert.ToBase64String(bytes);

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
        client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json; charset=UTF-8 "));`

Thank you,
Mario


Viewing all articles
Browse latest Browse all 58056

Trending Articles



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