【问题标题】:stackoverflow search apistackoverflow 搜索接口
【发布时间】:2011-05-17 12:49:54
【问题描述】:

我想使用stackoverflow API的搜索方法根据搜索关键字返回结果的json结构,然后在SearchResults div中显示这些结果(标题、描述和url)。

我是 C# 新手,我的第一次尝试是这样的:

    protected void searchStockOverflow(string y)
    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle="+y);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{ \"intitle\": \"" + y + "\"}";

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();

            SearchResults.InnerHtml += "<div style='border:1px solid blue;margin:5px;'>";
            SearchResults.InnerHtml += responseText + "<br />";
            SearchResults.InnerHtml += "</div><br style='clear:both;' />";
        }
    }

问题是返回的内容看起来像 dingbats 垃圾 - 我猜是因为它是序列化的并且需要反序列化?

【问题讨论】:

  • 很可能您需要更改字符串的编码
  • 你的函数名有错别字:searchStockOverflow :)

标签: c# json stackexchange-api


【解决方案1】:

我肯定会说考虑使用 REST 客户端;但是,要查看问题...通常您希望手动将数据反序列化为 JSON,然后通过您的 UI 代码运行该数据。例如:

static void SearchStackOverflow(string y)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle=" + Uri.EscapeDataString(y));
    httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
    httpWebRequest.Method = "GET";
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    string responseText;
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        responseText = streamReader.ReadToEnd();
    }
    var result = (SearchResult)new JavaScriptSerializer().Deserialize(responseText, typeof(SearchResult));
    .... do something with result ...
}
class SearchResult
{
    public List<Question> questions { get; set; }
}
class Question
{
    public string title { get; set; }
    public int answer_count { get; set; }
}

使用 System.Web.Extensions.dll 中的 JavaScriptSerializer

【讨论】:

  • +1 用于 JSON 反序列化和其他修复(URL 字符串转义,GET 与 POST)。但我认为不需要AutomaticDecompression,因为在HTTP 标头中没有指定Accept-Encoding 字段(即在httpWebRequest 中)。
  • @Groo - 是的,但是如果我发布一个不使用压缩的 SO API 示例,我很确定我的同事会嘲笑我(考虑到我在哪里工作等)。并且添加支持还会添加请求标头(我在提琴手中检查过)
【解决方案2】:

还可以查看Stacky StackApps .Net Client Library,它是基于 REST 的 API,提供对 stackoverflow 系列网站的访问。

【讨论】:

    【解决方案3】:

    很遗憾,我使用的是 Mac,无法对您的代码运行测试。您可能需要检查页面和返回的响应流的字符编码。如果它们不匹配;它可能会导致来自响应流的字符被错误地渲染,从而导致您看到的垃圾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 2019-10-13
      • 2013-06-25
      • 1970-01-01
      相关资源
      最近更新 更多