這可能是一個可能很簡單的問題,但我似乎無法格式化後的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();
}
乍一看,你的代碼看起來不錯。這個問題如何具體表現出來?什麼是例外? – 2009-04-21 15:06:43
例外情況是: 遠程服務器返回錯誤:(417)期望失敗。 – NickJ 2009-04-21 15:28:48
@NickJ:試試我的代碼如下。有效。 – Keltex 2009-04-21 15:32:48