2012-01-25 30 views
0

私はwiki pediaからデータを取得するためにwikipedia apiを使用していますが、ここでエラーが発生しています。私を助けてください。ここでwikipedia 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())。

関連する問題