2010-07-12 117 views
3

我是C#中的新成员,并且需要从C#中检索URL。大多数情况下它工作正常,但在一种情况下,它会抛出一个错误。 URL是如下 http://whois.afrinic.net/cgi-bin/whois?searchtext=41.132.178.138HttpWebRequest错误403

错误是:禁止(403):

异常在对URL的HTTP请求:http://whois.afrinic.net/cgi-bin/whois?searchtext=41.132.178.138远程服务器返回一个错误。

我的代码

void MyFUnction(string url) 
{ 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 

    request.UserAgent = ".NET Framework Test Client"; 
    request.ContentType = "application/x-www-form-urlencoded"; 
    Logger.WriteMyLog("application/x-www-form-urlencoded"); 


    // execute the request 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    // we will read data via the response stream 
    Stream resStream = response.GetResponseStream(); 

    string tempString = null; 
    int count = 0; 
    do 
    { 
     // fill the buffer with data 
     count = resStream.Read(buf, 0, buf.Length); 

     // make sure we read some data 
     if (count != 0) 
     { 
      // translate from bytes to ASCII text 
      tempString = Encoding.ASCII.GetString(buf, 0, count); 
      if (httpData == null) 
       httpData = tempString; 
      else 
       httpData += tempString; 

     } 
    } 
    while (count > 0); // any more data to read? 
} 
+0

格式化你的代码,在编辑器中选择它,按下Control-K。 – 2010-07-12 19:42:09

回答

6

删除您的ContentType线。

request.ContentType.... 

你不是在做表单文章,只用“GET”检索页面。

request.Method = "GET"; //this is the default behavior 

并且还将Accept属性设置为“text/html”。

request.Accept = "text/html"; 
+0

这很好。我在添加这三行代码之后成功完成了这个任务:'webRequest.Method =“GET”; webRequest.UserAgent =“Foo”; webRequest.Accept =“text/html”;' – swdev 2011-12-05 02:35:23

+1

尽管这篇文章已经很老了,但我今天已经投入了它,即2016年10月15日,因为今天我在试图学习WebScraping时也遇到过类似的问题。我在stackoverflow上发布了这个问题,但有人指出已经有类似的问题,因此我删除并搜索了可用的答案。上面给我的Shri Mikael Svenson给出的答案对解决我自己的问题真的很有帮助。好的@Mikael Svenson – Unnikrishnan 2016-10-15 13:11:51

4

设置

request.Accept = "text/html";
以及它会工作。

我不知道他们为什么配置这种方式,可能是故意阻止一些机器人。您可能想要检查他们的服务条款,无论您是否可以自动查询他们的网站。


编辑补充:仍然相信我的答案在这种情况下是正确的,我可以重现403,每次如果我不设置Accept头。 ContentType是多余的,但不是有害的。
在任何情况下,你还需要修改你的函数妥善处置的响应,并读取与正确的字符编码响应:

void MyFunction(string url) 
{ 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
    request.UserAgent = ".NET Framework Test Client"; 
    request.Accept = "text/html"; 
    Logger.WriteMyLog("application/x-www-form-urlencoded"); 

    // execute the request 
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
    { 
     // we will read data via the response stream 
     Stream resStream = response.GetResponseStream(); 
     StreamReader streamReader = new StreamReader(
             resStream, 
             Encoding.GetEncoding(response.CharacterSet) 
            ); 
     httpData = streamReader.ReadToEnd(); 
    } 
}