How to use HttpClient in Xamarin.Android to get keep-alive working

Liger_JeromeLiger_Jerome FRUniversity ✭✭

Hello,

I am using Xamarin.Android with a PCL. In my PCL, I use a HttpClient to Get or Post HTTP requests to an API. I want to use the same instance of my HttpClient for multiple HTTP requests, and to use the keep-alive.

Here is my code for test :

HttpClient c = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
c.Timeout = new TimeSpan(0, 0, 15);
c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", bufferItem.m_sAutorisationBasic);
c.DefaultRequestHeaders.Add("Connection", "Keep-Alive");

for (int i = 0; i < 5; i++)
{
    HttpRequestMessage t = new HttpRequestMessage(HttpMethod.Get, new Uri(bufferItem.m_sURL));
    HttpResponseMessage r = await c.SendAsync(t);
}

Unfortunately, sniffing those requests using the Android Application "Packet Capture" demonstrates that keep-alive is not working... As shown on the picture below, a TCP stream manage only one HTTP request :

Thanks to this very interesting post I have been able to get a real keep-alive working, but only for a "HEAD" request (I need it working for both GET and POST request). When I use the code above, and replace the HttpMethod.Get by HttpMethod.Head, I got keep-alive working, as shown below :

The post specifies that you need to "fully consume the response payload", that mean "reading bytes from the input stream until hitting the EOS byte", to get keep-alive working on Android.

Unfortunately, I don't understand what should I do to "fully consume my response"...

I use this code to consume my HttpResponseMessage, and keep-alive is not working :

HttpResponseMessage r = await c.SendAsync(t);
string content = await r.Content.ReadAsStringAsync();

Anyone can help with that please ? What am I doing wrong ?

Answers

Sign In or Register to comment.