我正在使用此代码在我的 Metro Style 应用程序中下载网页:
public static async Task<string> DownloadPageAsync(string url)
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
handler.AllowAutoRedirect = true;
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsString();
return responseBody;
}
问题是当 client.GetAsync(url)
行运行时,它会抛出一个异常:
发送请求时发生错误。
来自类型:HttpRequestException
。
编辑:
我已使用 InnerException 获取更多信息。抛出的第一个异常是 SocketException
,消息如下:
试图以访问权限禁止的方式访问套接字
在 System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
在 System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
编辑 2: 我已经从 Microsoft 下载并运行示例,但出现相同的错误: http://code.msdn.microsoft.com/windowsapps/HttpClient-Upload-Sample-f1abcc4e
编辑 3: 我在另一台机器上运行它并且运行良好。所以我想代码没有任何问题。我复制了解决方案,这意味着解决方案也没有问题。我正在尝试重新安装 Windows Developer Preview 以查看它是否可以解决我的问题。
最佳答案
好的。我找到了答案。异常是因为我在 Windows 8 Developer Preview 上安装了 NetLimiter 产品,它以某种方式阻止了我的应用程序访问互联网。
更新: 首先,这是适用于 每个 版本的 Windows 8 的代码。
public static async Task<string> DownloadPageAsync(string url)
{
try
{
HttpClientHandler handler = new HttpClientHandler { UseDefaultCredentials = true, AllowAutoRedirect = true };
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string html = await response.Content.ReadAsStringAsync();
return html;
}
catch (Exception)
{
return "";
}
}
其次,如果这不起作用,很可能是您的网络相关软件阻止了您的应用程序访问互联网。一个流行的案例是proxifier。如果您安装了代理程序,您的 MetroStyle 应用程序将无法访问互联网。要使其正常工作,请参阅我的博客:
http://anoori.me/blog/general/use-proxifier-in-windows-8-without-fiddler2
关于c# - 在 WinRT 中下载网页引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8300986/