问题描述
是否可以在 WinRT 中同时发送两个以上的 HTTP 请求?我正在尝试从服务器加载多个 JSON 文档,第二次调用后 HttpWebRequest 无法响应.以下是说明这一点的示例代码段:
Is it possible to send more than two HTTP requests concurrently in WinRT? I'm trying to load multiple JSON documents from a server and HttpWebRequest fails to respond after the second call. Here is a sample snippet that illustrates this:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
const string url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
const int iterations = 3;
var tasks = new List<Task>();
var ticks = DateTime.Now.Ticks;
for (var i = 0; i < iterations; i++)
{
// Create unique URL by appending a generated number.
var uniqueUrl = string.Format("{0}?v={1}", url, (i + ticks));
// Create the request.
var request = WebRequest.CreateHttp(uniqueUrl);
// Create the async task and store it for later.
var task = request.GetResponseAsync();
tasks.Add(task);
}
// Await all tasks in collection.
await Task.WhenAll(tasks);
Debugger.Break(); // <----- This will never break when iterations > 2
}
将此代码放在一个空白的MainPage.xaml.cs 中并使用迭代值.如果您将其设置为 2,则它可以工作.高于此值的任何操作都会失败.
Put this code in a blank MainPage.xaml.cs and play around with the iterations value. If you set it to 2, then it works. Anything above that, it will fail.
注意 :: 测试时不要使用 Fiddler.Fiddler 做了一些有趣的事情,它允许所有这些连接通过.我不知道怎么做,也不知道为什么.你可以自己测试一下.如果你在 fiddler 打开的情况下运行上面的代码,那么成功.
NOTE :: Do not use Fiddler when testing this. Fiddler does something funny and it allows all these connections to go through. I don't know how nor why. You can test this yourself. If you run the code above with fiddler open, then success.
注意 :: 这不是真正的代码.我只是用这个例子来说明这个问题.
NOTE :: This is not real code. I'm only using this example to illustrate the issue.
推荐答案
我没有尝试在 WinRT 中使用 WebClient
API,我只使用了 HttpClient
API(我在我的应用程序中广泛使用).
I haven't tried using the WebClient
API in WinRT, I've only used the HttpClient
API (which I'm using quite extensively in my application).
此代码有效:
const string url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
const int iterations = 10;
var tasks = new List<Task<HttpResponseMessage>>();
var ticks = DateTime.Now.Ticks;
for (var i = 0; i < iterations; i++)
{
// Create unique URL by appending a generated number.
var uniqueUrl = string.Format("{0}?v={1}", url, (i + ticks));
var handler = new HttpClientHandler();
var client = new HttpClient(handler)
{
BaseAddress = new Uri(uniqueUrl)
};
var task = client.GetAsync(client.BaseAddress);
tasks.Add(task);
}
// Await all tasks in collection.
await Task.WhenAll(tasks);
虽然您需要像这样异步读取所有响应,但取出响应正文有点乏味:
It is a bit more tedious to get out the response body though as you need to do an async read of all the responses like so:
var responseTasks = tasks.Select(task => task.Result.Content.ReadAsStringAsync());
await Task.WhenAll(responseTasks);
然后您可以遍历 responseTask
对象并获取它们的结果.
Then you can iterate through the responseTask
objects and take their result.
这篇关于WinRT/Win8 中的多个 HTTP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!