【问题标题】:WebClient returns 404 error, but this url works in the WebBrowser.Navigate methodWebClient 返回 404 错误,但此 url 在 WebBrowser.Navigate 方法中有效
【发布时间】:2012-10-26 04:38:46
【问题描述】:

我尝试使用WebClient 下载一个html 文件。

这是我的代码:

public string GetWebData(string url)
{
        string html = string.Empty;

        using (WebClient client = new WebClient())
        {
            Uri innUri = null;
            Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out innUri);

            try
            {
                client.Headers.Add("Accept-Language", " en-US");
                client.Headers.Add("Accept-Encoding", "gzip, deflate");
                client.Headers.Add("Accept", " text/html, application/xhtml+xml, */*");
                client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");

                using (StreamReader str = new StreamReader(client.OpenRead(innUri)))
                {
                    html = str.ReadToEnd();
                }
            }
            catch (WebException we)
            {
                throw we;
            }

            return html;
        }
    }

网址是http://www.paginegialle.it/roma-rm/abbigliamento/alberto-aspesi-c

但是我可以在 IE9 和 Firefox 和 Chrome 浏览器中导航到这个 URL,没有问题。我使用 Fiddler 来解决这个问题。

我发现WebClient.Request 之后的 URL 发生了变化 - 请参见下图:

实际网址:http://www.paginegialle.it/roma-rm/abbigliamento/alberto-aspesi-c.

请看区别。我删除了网址末尾的点。但它不适用于浏览器(IE9、Firefox、Chrome)。怎么把实际的url改成这个url?

请帮帮我。

【问题讨论】:

标签: winforms c#-4.0 uri webclient


【解决方案1】:

此行之后的网址是否仍然正确:

     Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out innUri);

我猜它适用于其他网站?

【讨论】:

【解决方案2】:

我认为您在 .NET URI 对象中发现了一个很酷的错误。

MessageBox.Show(new Uri("http://example.com/bug/here."));

显示:

http://example.com/bug/here

请注意缺少尾随句点。

猜你喜欢
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 2015-10-08
相关资源
最近更新 更多