c# - HttpWebRequest 错误 403

标签 c# .net

我是 C# 新手,需要从 C# 检索 url。大多数情况下它工作正常但在一种情况下它会抛出错误。网址如下 <强> 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?
}

最佳答案

删除您的 ContentType 行。

request.ContentType....

您不是在进行表单发布,只是使用“GET”检索页面。

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

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

request.Accept = "text/html";

关于c# - HttpWebRequest 错误 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3231674/

相关文章:

c# - 如何从 winform C# ping 数据库

c# - 最好的设计模式是什么?

c# - 如何处理 JsonConvert.DeserializeObject 中的空值/空值

c# - Withings API 和 C#

c# - .NET 正则表达式 - "Not"匹配

c# - LINQ 到 XML : Ignoring of the case of attributes

.net - DataTable 已属于另一个 DataSet

.net - 是否可以在同一进程中加载​​两个版本的 .NET 运行时?

.net - 在 VB.NET for WinForms 的禁用文本框中启用滚动条

c# - 使导航栏在 Xamarin.Forms 中消失