打开与服务器的连接时,我们的WinRT应用程序非常慢。请求需要大约500毫秒才能运行。这阻碍了我们的一些场景。
调试时,我们注意到当Fiddler处于活动状态时,请求速度更快 - 每个请求约100ms。稍后我们理解这是因为Fiddler在代理呼叫时使用了Keep-Alive连接,这使我们的代理呼叫更快。
我们以两种方式对此进行了双重检查。
我们尝试通过Connection头启用keep-alive(.Connection.Add(“Keep-Alive”))但这似乎没有任何影响 - 事实上,.NET似乎公然忽略了这个标题组件并没有根据请求发送(再次通过Fiddler检查)。
有没有人知道如何在Windows 8,WinRT,HttpClient类中为请求设置keep-alive?
答案 0 :(得分: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");
如果要关闭保持活动状态,请使用
client.DefaultRequestHeaders.Connection.Clear();
client.DefaultRequestHeaders.ConnectionClose = true;
答案 1 :(得分: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();
}
修改强> 由于您只想要GET,您可以使用:
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();
}