HttpWebRequest 403 Error

I am new to C # and have a requirement to get the url from C #. In most cases, it works fine, but in one case it throws an error. url is as follows http://whois.afrinic.net/cgi-bin/whois?searchtext=41.132.178.138

Error:

An exception was made in the HTTP request for the URL: http://whois.afrinic.net/cgi-bin/whois?searchtext=41.132.178.138 The remote server returned an error: (403) Forbidden.

My code is equal

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?
}
+3
source share
2 answers

Delete the line ContentType.

request.ContentType....

You do not make a message in the form, but only get the page using "GET".

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

Also set the Accept property to "text / html".

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

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();
    }
}
+4

Source: https://habr.com/ru/post/1754295/


All Articles