HttpWebRequest错误403

Cra*_*zyC 3 .net c#

我是C#的新手,需要从C#中检索网址.大多数情况下它工作正常,但在一个案例中它会引发错误.网址如下:http: //whois.afrinic.net/cgi-bin/whois?searchtext = 41.132.178.138

错误是:

url的HTTP请求中的异常:http://whois.afrinic.net/cgi-bin/whois?searchtext = 41.132.178.138远程服务器返回错误:(403)Forbidden.

我的代码是

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?
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*son 6

删除ContentType行.

request.ContentType....
Run Code Online (Sandbox Code Playgroud)

你没有做表格发布,只用"GET"检索页面.

request.Method = "GET"; //this is the default behavior
Run Code Online (Sandbox Code Playgroud)

并将Accept属性设置为"text/html".

request.Accept = "text/html";
Run Code Online (Sandbox Code Playgroud)