在WinRT的HttpClient类中使用Keep-Alive连接?

Sha*_*ish 3 c# windows-8 windows-runtime dotnet-httpclient windows-store-apps

打开与服务器的连接时,我们的WinRT应用程序速度极慢.请求需要大约500毫秒才能运行.这阻碍了我们的一些场景.

在调试时,我们注意到当Fiddler处于活动状态时,请求要快得多 - 每个请求约100ms.稍后我们理解这是因为Fiddler在代理呼叫时使用了Keep-Alive连接,这使我们的代理呼叫更快.

我们以两种方式对此进行了双重检查.

  1. 我们将UseProxy设置为false,并观察到请求变回缓慢.
  2. 我们关闭了Fiddler的"重用连接"选项,并观察到请求恢复得很慢.

我们尝试通过Connection头启用keep-alive(.Connection.Add("Keep-Alive"))但这似乎没有任何影响 - 事实上,.NET组件似乎公然忽略了标头,并且没有按要求发送(再次通过Fiddler检查).

有谁知道如何在Windows 8,WinRT,HttpClient类中为请求设置keep-alive?

小智 6

以下设置正确的标题为我启用keep-alive(客户端是一个HttpClient)

client.DefaultRequestHeaders.Connection.Clear();
client.DefaultRequestHeaders.ConnectionClose = false;
// The next line isn't needed in HTTP/1.1
client.DefaultRequestHeaders.Connection.Add("Keep-Alive");
Run Code Online (Sandbox Code Playgroud)

如果你想关闭keep-alive,请使用

client.DefaultRequestHeaders.Connection.Clear();
client.DefaultRequestHeaders.ConnectionClose = true;
Run Code Online (Sandbox Code Playgroud)


Ada*_*SFT 1

尝试使用 HttpContent 类添加标头 - 类似基于(但未经测试)http://social.msdn.microsoft.com/Forums/en-CA/winappswithcsharp/thread/ce2563d1-cd96-4380-ad41-6b0257164130

在幕后,HttpClient 使用 HttpWebRequest,这将使您可以直接访问 KeepAlive,但由于您正在通过 HttpClient,因此您无法直接访问 HttpWebRequest 类上的该属性。


public static async Task KeepAliveRequest()
{
    var handler = new HttpClientHandler();
    var client = new HttpClient(handler as HttpMessageHandler);

    HttpContent content = new StringContent(post data here if doing a post);
    content.Headers.Add("Keep-Alive", "true");

    //choose your type depending what you are sending to the server
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

    HttpResponseMessage response = await client.PostAsync(url, content);

    Stream stream = await response.Content.ReadAsStreamAsync();

    return new StreamReader(stream).ReadToEnd();
}


编辑 由于您只想获取,您可以使用以下方法来做到这一点:


public static async Task KeepAliveRequest(string url)
{
    var client = new HttpClient();
    var request = new HttpRequestMessage()
    {
        RequestUri = new Uri("http://www.bing.com"),
        Method = HttpMethod.Get,
    };
    request.Headers.Add("Connection", new string[] { "Keep-Alive" });
    var responseMessage = await client.SendAsync(request);
    return await responseMessage.Content.ReadAsStringAsync();
}