0

我正在使用 wikipedia api 从 wiki pedia 获取数据,但我在这里收到错误我发布我的代码和我的错误。请帮我。

HttpWebRequest myRequest =
    (HttpWebRequest)WebRequest.Create("http://en.wikipedia.org/w/api.php?action=opensearch&format=xml&search=hello");
System.Net.ServicePointManager.Expect100Continue = false;

using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse())
{
    string ResponseText;
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        ResponseText = reader.ReadToEnd();
    }

    lblresult.Text = ResponseText;
}

这是我的错误:

System.Net.WebException was unhandled by user code
  Message=The remote server returned an error: (403) Forbidden.
  Source=System
  StackTrace:
       at System.Net.HttpWebRequest.GetResponse()
       at _Default.btnsearch_Click(Object sender, EventArgs e) in c:\Users\Imran Ali\Desktop\Wikipedia\Default.aspx.cs:line 33
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 
4

1 回答 1

2

要访问 Wikipedia(使用或不使用 API),您必须在请求中设置User-Agent。这是因为维基媒体的用户代理政策

将 User-Agent 标头设置为什么?引用上面链接的政策页面:

脚本应使用包含联系信息的用户代理字符串,否则它们可能会被 IP 阻止,恕不另行通知。

如何设置标题?使用请求对象上的属性UserAgent

附带说明一下,对于像这样的简单请求,使用WebClient方法更容易,例如DownloadString().

于 2012-01-25T19:21:18.110 回答