Search stackoverflow api

I would like to use the stackoverflow API search method to return the json result structure based on the search keyword and then display those results (name, description and URL) in the SearchResults div.

I am new to C # and my first attempt did something like this:

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;' />"; } } 

The problem is that the returned one looks like dingbats frbish - I think because it is serialized and need to be deserialized?

+6
source share
3 answers

I would definitely think about using a REST client; however, to look at the problems ... usually you want to deserialize the data as JSON manually, and then run that data through your user interface code. For instance:

 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; } } 

What uses JavaScriptSerializer from System.Web.Extensions.dll

+8
source

Also check out the Stacky StackApps.Net Client Library , which is a REST interface that provides access to the stackoverflow website collection.

+3
source

Unfortunately, I am on my Mac and cannot run the test on your code. You might want to check the character encoding of both your page and the response stream. If they do not match; this can lead to the fact that the characters coming from the response stream will not display correctly, therefore, the garbage that you see.

0
source

Source: https://habr.com/ru/post/888315/


All Articles