WebClient返回404错误,但是该URL在WebBrowser.Navigate方法中有效

问题描述 投票:1回答:2

我尝试使用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;
        }
    }

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

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9QVzdFTC5wbmcifQ==” alt =“在此处输入图像描述”>

但是我可以在IE9,Firefox和Chrome浏览器中导航到该URL,而不会出现问题。我使用Fiddler解决了这个问题。

我发现WebClient.Request之后URL已更改-参见下图:

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

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9BYnNxTS5wbmcifQ==” alt =“在此处输入图像描述”>

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9qeG1mQS5qcGcifQ==” alt =“在此处输入图像描述”>

请注意区别。我将网址末尾的点删除。但是在浏览器(IE9,Firefox,Chrome)中无法使用。如何将实际网址更改为此网址?

请帮助我。

winforms c#-4.0 uri webclient
2个回答
0
投票

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

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

我猜它对其他网站也有用吗?


0
投票

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

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

显示:

http://example.com/bug/here

请注意,缺少尾随时间段。

© www.soinside.com 2019 - 2024. All rights reserved.