我想使用stackoverflow API的搜索方法,根据搜索关键字返回结果的json结构,然后在搜索结果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;' />";
}
}
问题是返回的内容看起来像丁蝙蝠垃圾 - 我猜是因为它是序列化的并且需要反序列化?
我肯定会说考虑使用 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的JavaScriptSerializer.dll
还可以看看Stacky StackApps .Net Client Library,这是一个基于REST的API,提供对stackoverflow系列网站的访问。
我在Mac上,无法对您的代码进行测试。您可能需要检查页面的字符编码和返回的响应流。如果它们不匹配;它可能会导致来自响应流的字符呈现不正确,从而导致您看到的垃圾。