WebRequest连接到Wikipedia API [英] WebRequest to connect to the Wikipedia API

查看:91
本文介绍了WebRequest连接到Wikipedia API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常简单的问题,但是我似乎无法格式化发布请求/响应以从维基百科API .如果有人可以帮助我解决问题,我已在下面发布了我的代码.

This may be a pathetically simple problem, but I cannot seem to format the post webrequest/response to get data from the Wikipedia API. I have posted my code below if anyone can help me see my problem.

    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即可登录Wikipedia).例如,尝试模拟此请求:

You might want to try a GET request first because it's a little simpler (you will only need to POST for wikipedia login). For example, try to simulate this request:

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.可以通过设置来解决:

The other problem he was experiencing on the POST request was, The exception is : The remote server returned an error: (417) Expectation failed. It can be solved by setting:

System.Net.ServicePointManager.Expect100Continue = false;

(这来自: HTTP POST返回错误:417预期失败." )

这篇关于WebRequest连接到Wikipedia API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆