无法通过HttpWebRequest获取HTML代码

我试图在http://odds.bestbetting.com/horse-racing/today解析页面的HTML代码,以便有一个种族列表,等等。问题是我无法检索HTML页面代码。 这是函数的C#代码:

public static string Http(string url) { Uri myUri = new Uri(url); // Create a 'HttpWebRequest' object for the specified url. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri); myHttpWebRequest.AllowAutoRedirect = true; // Send the request and wait for response. HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); var stream = myHttpWebResponse.GetResponseStream(); var reader = new StreamReader(stream); var html = reader.ReadToEnd(); // Release resources of response object. myHttpWebResponse.Close(); return html; } 

当我执行调用该函数的程序时,它会抛出exception

HttpWebResponse myHttpWebResponse =(HttpWebResponse)myHttpWebRequest.GetResponse();

这是:

无法处理从HTTP / HTTPS协议重定向到其他不同的协议。

我已经阅读了这个问题,但我似乎没有同样的问题。 我也尝试用狡猾的东西来嗅探流量,但是看不到它重定向的地方或类似的东西。 我刚刚提取了这两个可能的重定向:odds.bestbetting.com/horse-racing/2011-06-10/byCourse和odds.bestbetting.com/horse-racing/2011-06-10/byTime,但查询它们会产生与上述相同的结果。

这不是我第一次做这样的事情,但我真的迷失了这个。 有帮助吗?

谢谢!

您的问题可能有十几个可能的原因。

其中之一是来自服务器的重定向指向FTP站点,或类似的东西。

它也可能是服务器需要您未能提供的请求中的某些标头。

检查浏览器将发送到站点的内容并尝试复制。

我终于找到了解决方案……它实际上是标题的问题,特别是用户代理问题。

经过大量的搜索,我找到了一个与我同一个网站遇到同样问题的人。 虽然他的代码不同,但重要的是他将请求的UserAgent属性手动设置为浏览器的属性。 我想我以前做过这个,但我可能做得很糟糕…抱歉。

任何人感兴趣的最终代码是:

  public static string Http(string url) { if (url.Length > 0) { Uri myUri = new Uri(url); // Create a 'HttpWebRequest' object for the specified url. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri); // Set the user agent as if we were a web browser myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4"; HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); var stream = myHttpWebResponse.GetResponseStream(); var reader = new StreamReader(stream); var html = reader.ReadToEnd(); // Release resources of response object. myHttpWebResponse.Close(); return html; } else { return "NO URL"; } } 

非常感谢您的帮助。