Get All the Contacts From Gmail Using Google Data Protocol

How to Use Google Data Api

<html>
 <head><title>Get Authentication Token</title></head>
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <body>
  	<b>Get the Authentication  url from the google : </b><a href="token.do">click Here</a>
  </body>
</html>

Here is the general process to acquire an OAuth token for a given user

  1. Your registered web application makes a signed request for a request token at Google’s endpoint, https://www.google.com/accounts/OAuthGetRequestToken. Depending on the type of HTTP request being made, the required oauth_* query parameters can either be in the body of the request, as part of the Authorization header, or in the query part of the URL. In addition to the standard OAuth parameters, you must include a scope query parameter that is appropriate for the Google Data API(s) your application will interact with.
  2. Your web app sends the user to Google’s authorization endpoint, https://www.google.com/accounts/OAuthAuthorizeToken, referencing the request token and including the oauth_callback parameter. Google may prompt the user to log into their Google Account. Once authenticated with Google, the user chooses to share their data.
  3. The request token is authorized and Google redirects the user back to the URL you specified in the oauth_callback query parameter.
  4. Your web app sends a signed request to Google’s access token endpoint, https://www.google.com/accounts/OAuthGetAccessToken, to exchange the authorized request token for an access token.
  5. If the request is verified, Google responds with a valid access token.
  6. Your web app uses the access token to send signed requests to one or more of the Google Data APIs. The API(s) your application can interact with will depend on the value that was set in the initial scope query parameter.

Code For Getting auth token

</pre>
</pre>
package com.foo.bar;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.http.AuthSubUtil;
/**
 *
 * @author RAJENDRA
 * GmailToken class is used to create the authentication token for accessing the gmail account. In this class you have
 * to define your return back action name so after authentication you can return back on your website.
 */
public class GmailToken  extends HttpServlet{

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 String gmailAuthKey=getAuth();
 request.setAttribute("gmailAuthKey", gmailAuthKey);
 RequestDispatcher rd = getServletContext().getRequestDispatcher("/gmailToken.jsp");
 rd.forward(request, response);
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 doPost(request, response);
 }

 /**
 * The method is used to set the action url , so after authentication you can return back on your main website.
 * getting the token from the gmail
 * @return gmailAuthenticationToken
 */
 private String getAuth() {
 String authSubLogin=new String();
 String next = "http://localhost:8081/Gmail-Contacts/friends.do";
 String scope = "http://www.google.com/m8/feeds/";
 boolean secure = false;
 boolean session = true;
 authSubLogin = AuthSubUtil.getRequestUrl(next, scope, secure, session);
 return authSubLogin;
 }

}</pre>
<pre>
<pre>
<pre>
<pre>

Using Auth Token Access Gmail Api

After a successful authentication request, use the Auth value to create an Authorization header for each request to  the Google Data API:
Authorization: GoogleLogin auth=yourAuthToken

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title> Validate-the-email </title> </head> <body> <b>Validate the email id on the google account</b> <a href='<%=request.getAttribute("gmailAuthKey")%> />'>GMAIL</a> </body> </html>

package com.foo.bar;

import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.contacts.ContactQuery;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.util.ServiceException;
/**
 *
 * @author RAJENDRA
 * The GetAllContact class is used to validate and get all the contact list from your gmail.
 */
public class GetAllContact extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
		String token = req.getParameter("token");
		try {
			ContactFeed contactFeed = getContactList(token);
			req.setAttribute("contactFeed", contactFeed);
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		RequestDispatcher rd = getServletContext().getRequestDispatcher(
				"/showAllContacts.jsp");
		rd.forward(req, res);
	}

	public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
		doPost(req, res);
	}

	/**
	 * In this api we are setting the authentication token for the particular
	 * user and calling the google service
	 * @param token
	 * @return
	 * @throws IOException
	 * @throws GeneralSecurityException
	 * @throws ServiceException
	 */
	public ContactFeed getContactList(String token) throws IOException,GeneralSecurityException, ServiceException {
		ContactFeed contactFeed = null;
		try {
			ContactsService contactsService = new ContactsService(
					"GoogleInc-jsguide-1.0");
			contactsService.setAuthSubToken(token);
			contactFeed = getAllContacts(contactsService);
		} catch (Exception e) {
			e.printStackTrace();
		} catch (Error error) {
			error.printStackTrace();
		}
		return contactFeed;
	}

	/**
	 * Set other information regarding the email list and get the contact
	 * feed list
	 * @param myService
	 * @throws ServiceException
	 * @throws IOException
	 */
	public ContactFeed getAllContacts(ContactsService myService)
			throws ServiceException, IOException {
		URL feedUrl = new URL(
				"http://www.google.com/m8/feeds/contacts/default/full");
		ContactQuery contactQuery = new ContactQuery(feedUrl);
		contactQuery.setMaxResults(1000);
		ContactFeed resultFeed = myService.getFeed(contactQuery,
				ContactFeed.class);
		return resultFeed;
	}

}

Show All The Contacts On Jsp

<%@page import="com.google.gdata.data.contacts.ContactFeed"%> <html><head><title>Show all the email in my account</title></head><%@page import="com.google.gdata.data.contacts.ContactEntry" %><%@page import="com.google.gdata.data.extensions.Email"%><body><table>


<h1>ALL THE CONTACT FROM YOUR GMAIL CONTACT LIST<h1>
<%ContactFeed resultFeed = (ContactFeed)request.getAttribute("contactFeed");
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
 ContactEntry entry = resultFeed.getEntries().get(i);
  for (Email email : entry.getEmailAddresses()) {
       %><tr><td><b>Email add:</b></td><td><%=email.getAddress()%></td>
<%if (email.getRel() != null) { %> <% }if (email.getLabel() != null) {
 %><td><b>label</b></td><td> <%=email.getLabel()%></td></tr>
<% }if (email.getPrimary()) {}
%></table></body>
</html>

Access code from the google svn:

http://gmailcontact.googlecode.com/svn/trunk/





Advertisement

About rajnautiyal
Experience in Design and Development of web projects in struts,hibernate,springs,ajax,Flex . Development .Experienced in the implementation

3 Responses to Get All the Contacts From Gmail Using Google Data Protocol

  1. John Britto says:

    hai Iam a Java developer.I run the ur code but it will displays the error msg like this
    “”

  2. Narasimha says:

    Hi ,
    I’m a java developer and tried your code but it is giving the Exception
    The exception stack trace is
    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: Servlet execution threw an exception

    root cause

    java.lang.NoClassDefFoundError: com/google/gdata/client/http/AuthSubUtil
    com.foo.bar.GmailToken.getAuth(GmailToken.java:37)
    com.foo.bar.GmailToken.doPost(GmailToken.java:16)
    com.foo.bar.GmailToken.doGet(GmailToken.java:23)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 70 other followers