这可能是一个可悲的简单问题,但我似乎无法格式化帖子网络请求/响应以从维基百科API http://en.wikipedia.org/wiki/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();
}
您可能想首先尝试 GET 请求,因为它更简单一些(您只需要 POST 即可登录维基百科)。例如,尝试模拟这个请求:
这是代码:
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();
}
}
Edit:他在 POST 请求中遇到的另一个问题是,The exception is : The remote server returned an error: (417) Expectation failed.
可以通过设置来解决:
System.Net.ServicePointManager.Expect100Continue = false;
(这是来自:HTTP POST 返回错误:417“预期失败。” https://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c-resolved)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)