我正在使用维基百科api从wiki pedia获取数据但我在这里收到错误iam发布我的代码和我的错误。请帮帮我。
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:
答案 0 :(得分:2)
要访问Wikipedia(使用或不使用API),您必须在请求中设置User-Agent。这是因为Wikimedia's User-Agent policy。
将User-Agent标头设置为什么?引用上面链接的政策页面:
脚本应使用带有联系信息的信息性用户代理字符串,否则可能会被IP阻止,恕不另行通知。
如何设置标题?在请求对象上使用the UserAgent
property。
作为旁注,对于这样的简单请求,使用WebClient
方法更容易,例如,DownloadString()
。