2012-11-06 48 views
1

我尝试使用WebClient下载html文件。WebClient返回404错误,但此网址适用于WebBrowser.Navigate方法

这是我的代码:

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

enter image description here

但我可以导航到该网址在IE9和Firefox和Chrome浏览器没有问题。我用小提琴来解决这个问题。

我发现该网址具有WebClient.Request后改变 - 见下面的图片:

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

enter image description here

enter image description here

请看到其中的差别。我删除了网址结尾处的点。但它不适用于浏览器(IE9,Firefox,Chrome)。如何将实际的网址更改为此网址?

请帮帮我。

+2

[HttpWebRequest to URL with dot at end](http://stackoverflow.com/questions/856885/httpwebrequest-to-url-with-dot-at-the-end) – EricLaw

回答

0

是网络地址仍然是正确的这一行后:

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

我猜它适用于其他网站吗?

+0

谢谢你的支持有价值的答复。 请看到这个图片[图片] https://blufiles.storage.live.com/y1pZ77S7y4AIiEoW6NKKrBx1oKRVXoKoZ7u04P2IWZrauutal7L2Lj4Mg/Url%20Change%20%20After%20url%20conversion.png.jpg?psid=1&ck=0&ex=720 –

0

我想你已经在.NET URI对象中找到了一个很酷的bug。

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

显示:

http://example.com/bug/here

注意,尾随期间丢失。

+0

HTTP的杜佩://stackoverflow.com/questions/856885/httpwebrequest-to-url-with-dot-at-the-end – EricLaw