Xamarin Android HttpClient保持活跃状态​​

时间:2017-02-22 14:11:01

标签: c# asp.net xamarin xamarin.android dotnet-httpclient

我正在使用Xamarin.Android和PCL。在我的PCL中,我使用HttpClient来获取或发布对API的HTTP请求。 我希望将HttpClient的相同实例用于多个HTTP请求,并使用keep-alive。

这是我的测试代码:

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

不幸的是,在那里嗅探请求使用Android应用程序&#34;数据包捕获&#34;演示了keep-alive无效......如下图所示,TCP流只管理一个HTTP请求:

enter image description here

感谢this very interesting post我能够得到真正的保持活力,但仅限于&#34; HEAD&#34;请求(我需要它为GET和POST请求工作)。 当我使用上面的代码,并用 HttpMethod.Head 替换 HttpMethod.Get 时,我得到了keep-alive工作,如下所示:

enter image description here

The post指定您需要完全消耗响应有效负载&#34;,这意味着&#34;从输入流中读取字节,直到达到EOS字节&#34;,以保持 - 在Android上工作。

不幸的是,我不明白我应该做些什么来完全消费我的回应&#34; ......

我使用此代码来使用我的HttpResponseMessage,并且keep-alive不起作用:

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

任何人都可以提供帮助吗?我做错了什么?

0 个答案:

没有答案
相关问题