Searching for the News Headline
The idea is we will use API website from Bing search and retrieve the news about our players.
- Register at https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-news-search-api to get your API key.
- Open https://msdn.microsoft.com/en-us/library/dn760783.aspx#gettingnewsarticles
- Copy the JSON data.
- Create a new class named NewsSearch.
- Paste JSON as a class.
- Rename "Rootobject" to "NewsSearch"
- Back to Main class.
- Copy-paste the getGoogleHomePage function and rename it to GetNewsFromPlayer
Our GetNewsFromPlayer function looks like this.
public static string GetNewsFromPlayer()
{
var webClient = new WebClient();
byte[] googleHome = webClient.DownloadData("https://www.google.com");
using (var stream = new MemoryStream(googleHome))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
Change the variable name from "googleHome" to "searchResult". And the function takes playerName as an input.
public static string GetNewsFromPlayer(string playerName)
{
var webClient = new WebClient();
byte[] searchResult = webClient.DownloadData("https://www.google.com");
using (var stream = new MemoryStream(searchResult))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
Now, get an URL from the same page which you copy the JSON response. Use a string.Format method to dynamically replace the search based on the playerName. Then, the function looks like this.
public static string GetNewsFromPlayer(string playerName)
{
var webClient = new WebClient();
byte[] searchResult = webClient.DownloadData(string.Format("https://api.cognitive.microsoft.com/bing/v5.0/news/search?q={0}&mkt=en-us", playerName));
using (var stream = new MemoryStream(searchResult))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
Now, we want to customize the header of our HTTP request with our own API key.
webClient.Headers.Add("Ocp-Apim-Subscription-Key", "9e6467bf15cd4474a72b807d647ecae7");
Finally, we called the function from Main method.
Console.WriteLine(GetNewsFromPlayer("Diego valeri"));