2012-01-25 61 views
0

我使用維基百科API來從維基百科獲取數據,但我在這裏得到錯誤iam張貼我的代碼和我的錯誤。請幫幫我。使用維基百科API錯誤

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

服務器是否也返回錯誤頁面中的任何*文本*?這可能會告訴你爲什麼你會得到403.我沒有得到相同的API請求403,所以他們可能會阻止你的IP。 –

回答

2

維基百科(使用API​​或沒有),你必須設置一個User-Agent在請求訪問。這是因爲Wikimedia's User-Agent policy

如何設置User-Agent標頭?引用上面鏈接的策略頁面:

Scripts should use an informative User-Agent string with contact information, or they may be IP-blocked without notice.

如何設置標題?在請求對象上使用the UserAgent property

請注意,對於這樣的簡單請求,使用WebClient方法更容易,例如,DownloadString()