2009-04-21 115 views
10

這可能是一個可能很簡單的問題,但我似乎無法格式化後的webrequest /響應從Wikipedia API獲取數據。如果有人能幫我看看我的問題,我已經在下面發佈了我的代碼。WebRequest連接到維基百科API

string pgTitle = txtPageTitle.Text; 

    Uri address = new Uri("http://en.wikipedia.org/w/api.php"); 

    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; 

    request.Method = "POST"; 
    request.ContentType = "application/x-www-form-urlencoded"; 

    string action = "query"; 
    string query = pgTitle; 

    StringBuilder data = new StringBuilder(); 
    data.Append("action=" + HttpUtility.UrlEncode(action)); 
    data.Append("&query=" + HttpUtility.UrlEncode(query)); 

    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); 

    request.ContentLength = byteData.Length; 

    using (Stream postStream = request.GetRequestStream()) 
    { 
     postStream.Write(byteData, 0, byteData.Length); 
    } 

    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
    { 
     // Get the response stream. 
     StreamReader reader = new StreamReader(response.GetResponseStream()); 

     divWikiData.InnerText = reader.ReadToEnd(); 
    } 
+1

乍一看,你的代碼看起來不錯。這個問題如何具體表現出來?什麼是例外? – 2009-04-21 15:06:43

+0

例外情況是: 遠程服務器返回錯誤:(417)期望失敗。 – NickJ 2009-04-21 15:28:48

+0

@NickJ:試試我的代碼如下。有效。 – Keltex 2009-04-21 15:32:48

回答

6

你可能想先嚐試一個GET請求,因爲這是一個有點簡單(你只需要發佈的維基百科登錄)。例如,嘗試模擬這個請求:

http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page

下面的代碼:

HttpWebRequest myRequest = 
    (HttpWebRequest)WebRequest.Create("http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page"); 
using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse()) 
{ 
    string ResponseText; 
    using (StreamReader reader = new StreamReader(response.GetResponseStream())) 
    { 
     ResponseText = reader.ReadToEnd(); 
    } 
} 

編輯:另一個問題,他正在經歷的POST請求,The exception is : The remote server returned an error: (417) Expectation failed.可以通過設置解決:

(這是來自:HTTP POST Returns Error: 417 "Expectation Failed."

0

您似乎在HTTP POST上推送輸入數據,但似乎您應該使用HTTP GET。

從MediaWiki的API文檔:

The API takes its input through parameters in the query string. Every module (and every action=query submodule) has its own set of parameters, which is listed in the documentation and in action=help, and can be retrieved through action=paraminfo. http://www.mediawiki.org/wiki/API:Data_formats

1

我目前正處於實現C#MediaWiki API的最後階段,該API允許輕鬆編寫大多數MediaWiki查看和編輯操作的腳本。

主要API是在這裏:http://o2platform.googlecode.com/svn/trunk/O2%20-%20All%20Active%20Projects/O2_XRules_Database/_Rules/APIs/OwaspAPI.cs這裏是正在使用的API的例子:

var wiki = new O2MediaWikiAPI("http://www.o2platform.com/api.php"); 

wiki.login(userName, password); 

var page = "Test"; // "Main_Page"; 

wiki.editPage(page,"Test content2"); 

var rawWikiText = wiki.raw(page); 
var htmlText = wiki.html(page); 

return rawWikiText.line().line() + htmlText;