我正在使用此代码在我的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) 运行,它引发了一个例外,说:

An error occurred while sending the request. 从类型: HttpRequestException.

编辑:

我使用Innerexception获取更多信息。第一个例外是 SocketException 下面的消息:

An attempt was made to access a socket in a way forbidden by its access permissions

at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)

at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)

编辑2:我已经下载并从Microsoft运行了示例,我得到了相同的错误:http://code.msdn.microsoft.com/windowsapps/httpclient-upload-sample-f1abcc4e

The error is shown in the picture

编辑3:我在另一台计算机上运行了此操作,它运行良好。因此,我想代码没有错。我复制了解决方案,这也意味着解决方案也没有错。我正在尝试重新安装Windows Developer预览,以查看它是否解决了我的问题。

有帮助吗?

解决方案

好的。我找到了答案。例外是因为我在Windows 8 Developer Preview上安装了NetBlimiter产品,并以某种方式阻止了我的应用程序访问Internet。

更新:首先,这是工作中的代码 每一个 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 "";
        }
    }

其次,如果这种情况不起作用,则可能会有一个与网络相关的软件,以阻止您的应用访问Internet。一个受欢迎的案例是 代理商. 。如果您已安装了主观器 您的地铁应用将无法访问Internet。 为了使其正常工作,请参考我的博客:

http://anoori.me/blog/general/use-proxifier-in-windows-8-without-fiddler2

其他提示

可以肯定的是,NetLimiliter正在通过本地主机代理运行您的Internet请求,并且您的应用程序没有“本地网络”功能,该功能将允许此类访问本地网络

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top