Nic*_*ckJ 10 c# mediawiki wikipedia webrequest wikipedia-api
这可能是一个非常简单的问题,但我似乎无法格式化web webrequest /响应以从Wikipedia 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();
}
Run Code Online (Sandbox Code Playgroud)
您可能希望首先尝试GET请求,因为它更简单一些(您只需要POST以进行维基百科登录).例如,尝试模拟此请求:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:他在POST请求中遇到的另一个问题是,The exception is : The remote server returned an error: (417) Expectation failed.可以通过设置来解决:
System.Net.ServicePointManager.Expect100Continue = false;
Run Code Online (Sandbox Code Playgroud)
(这来自:HTTP POST返回错误:417"期望失败.")
| 归档时间: |
|
| 查看次数: |
14640 次 |
| 最近记录: |