Wednesday, 17 October 2012

Twitter oauth guideline with Example

About:

By  using this blog you can access data from twitter Server on OAuth standard. Twitter will give all data of a particular user except  password. So that you can use it in your product development.you can do this by using Facebook and Google too.Hopefully i will post all that stuff later on.

Recently i have finished one application related to Twitter oauth where i face many problem while developing  because i didn't find one good documentation from internet.
So if you are one of them then relay this blog will be very useful to you

To Develop this several third party apis are there but basically i use Twitter-4j api.
Follow the below guideline for Getting start.

Pre-Requirements:

1.Any live hosting server in testing or developing mood.(because call back url will not work for localhost)
2.A twitter account
3.Twitter4J API: you need twitter4j-core-[verson].jar to your built path
4.You can refer api Doc

Getting Start/Register one App with Twitter:

1.Create a new application on twitter development environment
2.Click on create new application.
                         

3. Fill-up the details as shown in below screen shot

                                 
    Name:your app name any thing(in my case getRef)
    Description:what is the motto of your app(you can get......)
   Website:your publicly available web site where you are planing to deploy your app.
   callback URL:  Give one hosting environment address because in local host it will not work
   click on create your twitter application

4.Click on create a new application:
  it will give you the following details listed below
      Consumer key
Consumer secret
Request token URL
Authorize URL
Access token URL
Callback URL

5. it's important in callback URL don't give you localhost
    it will not work
    twitter has already remover that option
    so use any live hosting environment and for students use any free cloud server
    for deploy your app by loin for personal use
    eg:-Google app engine,amazon cloud server

    later you will use all the information above while developing your application so note it down.


Example:

Here i use spring-mvc and Google app engine for Deploying this application.In face you can use ioc for injection dependency.

1.i use one Controller to handle all this stuff(GetDataFromTwitter.java) infect you can use servlet also
2.One jsp page to redirect to my app(Welcome.jsp)/optional one
3.Another jsp to ask conformation before redirecting to twitter server(login.jsp)
4.Another one for Displaying the user details. Infect you can  use the user  details/information for further business processing.But in order to complete this blog i display the user information(success.jsp).


Welcome.jsp:(Just for the worm welcome any way this is optional one)

=========================================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style type="text/css">
div#body1{
position:absolute;
top:400px;
left:600px;
}

</style>
</head>
<body>
<div id="header1">
<font color="#0EA5B9" size="4" style="top: 351px;left: 491px;position: absolute;">Click Below Image to Fetch details from Twitter</font>
<div id="body1">
<a href="/requesttwitter"><img src="../image/logo.png"></a>
</div>
</div>
</body>
</body>
</html>
===========================================

GetDataFromTwitter.java:(all business Details)

========================================================
package com.acti.controller;
imports........................;

@Controller
@RequestMapping(value="/")
public class GetDataFromTwitter {

   // This is the consumer key for this application
    private String consumer_key =copy it from your refistred app;

    // This is the consumer secret for this application
    private String consumer_secret = copy it from your registred app;

//Step-1(just for welcome file list)
    @RequestMapping(value="/",method=RequestMethod.GET)
    public String welcome(HttpServletRequest request,HttpServletResponse response) throws     TwitterException{
    return "welcome";
    }
 /Step-2(/from welcome.jsp it will come hear)
@RequestMapping(value="/requesttwitter",method=RequestMethod.GET)
    public String getDetails(HttpServletRequest request,HttpServletResponse response) throws TwitterException{
   
    Twitter twitter = new TwitterFactory().getInstance();
twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumer_key, consumer_secret);
    //AccessToken requestToken=twitter.getOAuthAccessToken();
    RequestToken requestToken= twitter.getOAuthRequestToken();
    String token = requestToken.getToken();
    String tokenSecret = requestToken.getTokenSecret();
    HttpSession session = request.getSession();
    session.setAttribute("token", token);
    session.setAttribute("tokenSecret", tokenSecret);
    session.setAttribute("requesttoken", requestToken);
    System.out.println("Token "+token);
    System.out.println("TokenSecrate "+tokenSecret);
    String authUrl = requestToken.getAuthorizationURL();
    request.setAttribute("authUrl", authUrl);
    System.out.println("url"+authUrl);
    return "login";
   
    }
//Step-3(call back url in my case XXXX.appsport.com/getdata what you have registred curing creation of app)
@RequestMapping(value="/getdata",method=RequestMethod.GET)
public String afterAuthentication(HttpServletRequest request,HttpServletResponse response) throws IOException{
                //create one UserDetails pojo with setter and getter method
UserDetails user_Details=new UserDetails();
PrintWriter out=response.getWriter();
HttpSession session = request.getSession(false);
if(session!=null){
try{
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumer_key,consumer_secret);
AccessToken accessToken = twitter.getOAuthAccessToken((RequestToken) session.getAttribute("requesttoken"));
twitter.setOAuthAccessToken(accessToken);
//User is a object which contain all the user information details
User user=twitter.verifyCredentials();
user_Details.setUser_Name(user.getName());
System.out.println("seventh");
user_Details.setFrineds_count(user.getListedCount());
user_Details.setUser_Location(user.getLocation());
user_Details.setGet_id(user.getId());
user_Details.setGetLanguage(user.getLang());
user_Details.setUser_url(user.getURL().getPath());
user_Details.setProfile_image(user.getProfileImageURL().getPath());
user_Details.setGettime_Zone(user.getTimeZone());
session.setAttribute("user", user_Details);
}catch (TwitterException twitterException) {
// TODO: handle exception
//your error handling mechanism
}
}
return "sucess";
}
}
=========================================================

login.jsp:( for getting conformation)

=======================================

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<style type="text/css">
a{
text-decoration : none;
}
a:link {
color: green;
font-weight: bold;
}
a:visited {
color:green;
font-weight: bold;
}
a:hover{
color: red;
font-size: 20px
}
div.common{
font-weight: bold;
position: relative;
left: 500px;
top: 382px;
}
}
/* a:visited{
color:yellow;
} */
</style>

</head>
<body>
<div class="common">
<font color="red" size="4">We need your permission</font><br><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <a href='<%=request.getAttribute("authUrl") %>'>Click to conform</a>
</div>
</body>
</html>

======================================

success.jsp (to see user details)

==================================

<%@ page language="java" import="com.acti.dto.UserDetails;" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="user" class="com.acti.dto.UserDetails" scope="session"/>
 <table border="0"  cellpadding="0" cellspacing="0" 
height="40%" width="40%">
          <tr>
             <td><FONT SIZE="4" COLOR="#333399">We fetch the Following Information from Twitter</FONT><BR></td>
          </tr>
             <td><B>Name:</B></td>
             <td> <%= user.getUser_Name() %></td>
          </tr>
          <tr>
             <td><B>Id</B></td>
             <td> <%= user.getGet_id() %></td>
          </tr>
           <tr>
             <td><B>Location</B></td>
             <td> <%= user.getUser_Location()%></td>
          </tr>
           <tr>
             <td><B>Language</B></td>
             <td> <%= user.getGetLanguage() %></td>
          </tr>
           <tr>
             <td><B>TimeZone</B></td>
             <td> <%= user.getGettime_Zone()%></td>
          </tr>
           <tr>
             <td><B>Number of Friend</B></td>
             <td> <%= user.getFrineds_count() %></td>
          </tr>
           <tr>
             <td><B>View Profile</B></td>
             <td> <a href="<%= user.getUser_url()%>">click</a></td>
          </tr>
          
</table>
</body>
</html>
===================================



Ok if you fill that this post is really helping you then please don't forgot  to post comment,compliment or suggestion because it will give me more inspiration and energy for further posting.
Finally i will say thank you for your patience











Skype Me™!

No comments:

Post a Comment