Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET
Tip/Trick

Simple Google News API

Rate me:
Please Sign up or sign in to vote.
4.87/5 (13 votes)
26 Mar 2014CPOL 61.5K   1.9K   16   13
Google API for NEWS

Introduction

In this tip, I am going to discuss about Google news API.

Background

I have used HttpWebRequest and HttpWebResponse for retrieving news from Google API URL. I have written all code for that....

I have one textbox for insert search parameters and one button for search data using Google API.

When we click on Get News button, it calls JavaScript GetNews() function.

From JavaScript function, Ajax post method calls web method from code behind.

Google News content has been retrieved using HttpWebRequest and HttpWebRequest, this WebMethod returns data into array format from code behind.

Now Div having name "DivNews" has been appended for showing news content using jQuery.

For further details, please take a look at the code.

Using the Code

1) News.aspx

JavaScript Code

JavaScript
<script type="text/javascript" src="Scripts/jquery-2.1.0.min.js"></script>
<script>

    //For Enter Key Press Event
    function runScript(e) {
        if (e.keyCode == 13) {

            //Call GetNews Function
            GetNews();

            return false;
        }
    }

    //Function for GetNews Using Ajax Post Method
    function GetNews() {

        //Set FadeIn for Progressive Div
        $("#ProgressiveDiv").fadeIn();

        //Create Ajax Post Method
        $.ajax({
            type: "POST", // Ajax Method
            url: "News.aspx/GetNewsContent",  //Page URL / Method name
            data: "{'NewsParameters':'" +
            document.getElementById("txtSubject").value + "'}", // Pass Parameters
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (data) { // Function call on success

                $("#DivNews").empty(); // Set Div Empty

                //Set For loop for binding Div Row wise
                for (var i = 0; i < data.d.length; i++) {

                    //Design Div Dynamically using append
                    $("#DivNews").append("<tr><td>
                    <B style='color:Red'>" + data.d[i].title +
                    "- By: Nirav Prabtani</B> </td></tr><tr><td>" +
                    data.d[i].Description + "</td></tr>");
                }

                //set fadeOut for ProgressiveDiv
                $("#ProgressiveDiv").fadeOut(500);
            },

            error: function (result) { // Function call on failure or error
                alert(result.d);
            }
        });
    }
</script>

CSS Code

CSS
<style type="text/css">
     .classname
     {
         -moz-box-shadow: inset 0px 1px 0px 0px #ffffff;
         -webkit-box-shadow: inset 0px 1px 0px 0px #ffffff;
         box-shadow: inset 0px 1px 0px 0px #ffffff;
         background: -webkit-gradient( linear, left top,
         left bottom, color-stop(0.05, #ededed), color-stop(1, #dfdfdf) );
         background: -moz-linear-gradient( center top, #ededed 5%, #dfdfdf 100% );
         filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ededed', endColorstr='#dfdfdf');
         background-color: #ededed;
         -webkit-border-top-left-radius: 6px;
         -moz-border-radius-topleft: 6px;
         border-top-left-radius: 6px;
         -webkit-border-top-right-radius: 6px;
         -moz-border-radius-topright: 6px;
         border-top-right-radius: 6px;
         -webkit-border-bottom-right-radius: 6px;
         -moz-border-radius-bottomright: 6px;
         border-bottom-right-radius: 6px;
         -webkit-border-bottom-left-radius: 6px;
         -moz-border-radius-bottomleft: 6px;
         border-bottom-left-radius: 6px;
         text-indent: 0;
         border: 1px solid #dcdcdc;
         display: inline-block;
         color: #777777;
         font-family: arial;
         font-size: 15px;
         font-weight: bold;
         font-style: normal;
         height: 25px;
         line-height: 50px;
         width: 100px;
         text-decoration: none;
         text-align: center;
         text-shadow: 1px 1px 0px #ffffff;
     }
     .classname:hover
     {
         background: -webkit-gradient( linear, left top,
         left bottom, color-stop(0.05, #dfdfdf), color-stop(1, #ededed) );
         background: -moz-linear-gradient( center top, #dfdfdf 5%, #ededed 100% );
         filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#dfdfdf', endColorstr='#ededed');
         background-color: #dfdfdf;
     }
     .classname:active
     {
         position: relative;
         top: 1px;
     }

     .textbox
     {
         background: #FFF url(http://html-generator.weebly.com/files/theme/input-text-9.png) no-repeat 4px 4px;
         border: 1px solid #999;
         outline: 0;
         padding-left: 25px;
         height: 25px;
         width: 275px;
     }
     .style1
     {
         height: 61px;
     }
     #ProgressiveDiv
     {
         width: 100%;
         height: 100%;
         display: none;
         opacity: 0.4;
         position: fixed;
         top: 0px;
         left: 0px;
         vertical-align: middle;
     }
 </style>

HTML Code

HTML
  <body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td align="center" class="style1">
                    <h3>
                        Welcome to My news Portal</h3>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:TextBox runat="server" ID="txtSubject" 
                    CssClass="textbox" onkeypress="return runScript(event)" />
                </td>
            </tr>
            <tr>
                <td align="right">
                    <h6 style="height: 35px">
                        By: Nirav Prabtani</h6>
                </td>
            </tr>
        </table>
        <div id="DivNews">
        </div>

    </div>
    <%--This Div is For Binding News--%>
    <div id="ProgressiveDiv" style="padding-left: 500px">
        <img src="Image/loading.gif" />
    </div>
    </form>
</body> 

2) News.aspx.cs

All news content from Google API has been retrieved using webMethod from code behind.

C# Code

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Net;
using System.IO;
using System.Text;
using System.Data;

namespace GoogleNews_API
{
    public partial class News : System.Web.UI.Page
    {
        //Page Load Method
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        //WenMethod GetNewsContent for Retrieving News from Google API
        [WebMethod]
        public static ItemNews[] GetNewsContent(string NewsParameters)
        {

            List<ItemNews> Details = new List<ItemNews>();

            // httpWebRequest with API URL
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create
            ("http://news.google.com/news?q=" + NewsParameters + "&output=rss");

            //Method GET
            request.Method = "GET";

            //HttpWebResponse for result
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();


            //Mapping of status code
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = null;

                if (response.CharacterSet == "")
                    readStream = new StreamReader(receiveStream);
                else
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

                //Get news data in json string

                string data = readStream.ReadToEnd();

                //Declare DataSet for putting data in it.
                DataSet ds = new DataSet();
                StringReader reader = new StringReader(data);
                ds.ReadXml(reader);
                DataTable dtGetNews = new DataTable();

                if (ds.Tables.Count > 3)
                {
                    dtGetNews = ds.Tables["item"];

                    foreach (DataRow dtRow in dtGetNews.Rows)
                    {
                        ItemNews DataObj = new ItemNews();
                        DataObj.title = dtRow["title"].ToString();
                        DataObj.link = dtRow["link"].ToString();
                        DataObj.item_id = dtRow["item_id"].ToString();
                        DataObj.PubDate = dtRow["pubDate"].ToString();
                        DataObj.Description = dtRow["description"].ToString();
                        Details.Add(DataObj);
                    }
                }
            }

            //Return News array 
            return Details.ToArray();
        }

        //Define Class to return news data
        public class ItemNews
        {
            public string title { get; set; }
            public string link { get; set; }
            public string item_id { get; set; }
            public string PubDate { get; set; }
            public string Description { get; set; }
        }
    }
} 

Final Output

Image 1

History

  • 26th Mar 2014: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader eInfochips
India India



Nirav Prabtani




I am a team lead, Database Architect and Designer /Technical Architect/Analyst,
Programmer in Microsoft .NET Technologies & Microsoft SQL Server with more than
4.5 years of hands on experience.



I love to code....!!! Smile | :)



My recent past includes my work with the education domain as a technical business
requirement analyst, database architect & designer and analyst programmer; just
love my involvement with the world of knowledge, learning and education and I think
I know quite well what I want to do in life & in my career. What do I like? Well,
ideation, brainstorming, coming up with newer and more creative ways of doing things;
each time with an enhanced efficiency. An item in my day's agenda always has a task
to look at what I did yesterday & focus on how I can do it better today




Contact Me

Nirav Prabtani


Mobile : +91 738 308 2188



Email : niravjprabtani@gmail.com


My Blog:
Nirav Prabtani



Comments and Discussions

 
QuestionSimple Google News API Pin
Member 1316785819-Mar-19 23:38
Member 1316785819-Mar-19 23:38 
Questionis this working now? Pin
Google News Trends9-May-18 20:03
Google News Trends9-May-18 20:03 
QuestionNews Feed Error Pin
KamalaKannan Ramesh6-Mar-18 0:17
KamalaKannan Ramesh6-Mar-18 0:17 
Questionresponse is returning Pin
Member 78646728-Dec-16 6:37
Member 78646728-Dec-16 6:37 
AnswerRe: response is returning Pin
Nirav Prabtani9-Dec-16 20:27
professionalNirav Prabtani9-Dec-16 20:27 
QuestionHow to get news by a specific date in fromat yyyy-mm-dd or else? Pin
Member 125086298-May-16 10:57
Member 125086298-May-16 10:57 
QuestionGoogle API Alerts Update Pin
dilking20021-Dec-14 9:25
dilking20021-Dec-14 9:25 
Questionerror Pin
zaib fatima22-Oct-14 1:53
zaib fatima22-Oct-14 1:53 
GeneralGood work Nirav Pin
karthik Udhayakumar24-May-14 16:18
professionalkarthik Udhayakumar24-May-14 16:18 
GeneralRe: Good work Nirav Pin
Nirav Prabtani17-Jun-14 1:38
professionalNirav Prabtani17-Jun-14 1:38 
QuestionGood Job Pin
jrooks101727-Mar-14 7:02
professionaljrooks101727-Mar-14 7:02 
Generalmy vote of 5 Pin
Southmountain26-Mar-14 6:08
Southmountain26-Mar-14 6:08 
GeneralRe: my vote of 5 Pin
Nirav Prabtani26-Mar-14 6:40
professionalNirav Prabtani26-Mar-14 6:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.