Searching for the News Headline

The idea is we will use API website from Bing search and retrieve the news about our players.

  1. Register at https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-news-search-api to get your API key.
  2. Open https://msdn.microsoft.com/en-us/library/dn760783.aspx#gettingnewsarticles
  3. Copy the JSON data.
  4. Create a new class named NewsSearch.
  5. Paste JSON as a class.
  6. Rename "Rootobject" to "NewsSearch"
  7. Back to Main class.
  8. 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"));

results matching ""

    No results matching ""