Press enter to see results or esc to cancel.


JAVA – Facebook graph API-Get user Posts


In this video, I have shown how you can generate Access token dynamically. And use the dynamic access to get facebook user and facebook user posts using facebook graph API.
Here is the steps what you have to follow.
1. Login to facebook developers site and get an APP id by creating a facebook APP.

2. Grant permission for your Domain to access the Facebook app. You can go to this link Grant Permission for the steps.
3. Project Structure in Eclipse IDE.

4.Update the APP ID in the page index.jsp
index.jsp

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
 // This is called with the results from from FB.getLoginStatus().
 function statusChangeCallback(response) {
 console.log('statusChangeCallback');
 console.log(response);
 console.log(response.authResponse.accessToken);
 //alert(response.authResponse.accessToken);
 if (response.status === 'connected') {
 window.location.href='Sign_in_Controller.jsp?access_token='+response.authResponse.accessToken; 
 } else {
 // The person is not logged into your app or we are unable to tell.
 document.getElementById('status').innerHTML = 'Please log ' +
 'into this app.';
 }
 }
 // This function is called when someone finishes with the Login
 // Button. See the onlogin handler attached to it in the sample
 // code below.
 function checkLoginState() {
 FB.getLoginStatus(function(response) {
 statusChangeCallback(response);
 });
 }
 window.fbAsyncInit = function() {
 FB.init({
 appId : 'FILL THE APP ID',
 cookie : true, // enable cookies to allow the server to access 
 // the session
 xfbml : true, // parse social plugins on this page
 version : 'v2.8' // use graph api version 2.8
 });
 FB.getLoginStatus(function(response) {
 statusChangeCallback(response);
 });
 };
 // Load the SDK asynchronously
 (function(d, s, id) {
 var js, fjs = d.getElementsByTagName(s)[0];
 if (d.getElementById(id)) return;
 js = d.createElement(s); js.id = id;
 js.src = "https://connect.facebook.net/en_US/sdk.js";
 fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));
 // Here we run a very simple test of the Graph API after login is
 // successful. See statusChangeCallback() for when this call is made.
</script>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>

5. After successful login, The page will be redirected to Sign_in_Controller.jsp to save access token and user information in sessions.
Sign_in_Controller.jsp


<%@page import="com.chillyfacts.com.profile.Profile_Bean"%>
<%@page import="com.chillyfacts.com.profile.Profile_Modal"%>
<%@ 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>
</head>
<body>
<%
String access_token=(String)request.getParameter("access_token");
Profile_Modal obj_Profile_Modal=new Profile_Modal();
Profile_Bean obj_Profile_Bean= obj_Profile_Modal.call_me(access_token);
obj_Profile_Bean.setAccess_token(access_token);
session.setAttribute("fb_user_session", obj_Profile_Bean);
%>
<script type="text/javascript">
window.location.href="Profile_Page.jsp";
</script>
</body>
</html>

6.Profile_Page.jsp

<%@page import="java.util.Iterator"%>
<%@page import="com.chillyfacts.com.posts.Post_Use_Bean"%>
<%@page import="java.util.List"%>
<%@page import="com.chillyfacts.com.posts.Post_Modal"%>
<%@page import="com.chillyfacts.com.profile.Profile_Bean"%>
<%@ 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>
</head>
<body>
<%
Profile_Bean obj_Profile_Bean=(Profile_Bean)session.getAttribute("fb_user_session");
%>
<center>
<table border="1">
<tr>
<td colspan="2" align="center">
<h2>Profile Page</h2>
</td>
</tr>
<tr>
<td align="center">
<img src="<%=obj_Profile_Bean.getProfile_picture() %>"></img><br>
Name : <%=obj_Profile_Bean.getUser_name() %><br>
id : <%=obj_Profile_Bean.getId() %><br>
</td>
<td>
<%
Post_Modal obj_Post_Modal=new Post_Modal();
List<Post_Use_Bean> list_of_posts= obj_Post_Modal.call_me_to_get_posts(obj_Profile_Bean.getAccess_token());
Iterator<Post_Use_Bean> it_list_of_posts=list_of_posts.iterator();
if(list_of_posts.size()>0){
Post_Use_Bean obj_Post_Use_Bean=new Post_Use_Bean();
while(it_list_of_posts.hasNext()){
obj_Post_Use_Bean=it_list_of_posts.next();
%>
<%=obj_Post_Use_Bean.getId() %><br>
<%=obj_Post_Use_Bean.getMessage() %><br>
<%=obj_Post_Use_Bean.getCreated_time() %><br>
<hr>
<%
}
}
%>
</td>
</tr>
</table>
</center>
</body>
</html>

7. Post_Modal.java


package com.chillyfacts.com.posts;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class Post_Modal {
      public List < Post_Use_Bean > call_me_to_get_posts(String access_token) throws Exception {
        List < Post_Use_Bean > list_posts = new ArrayList < Post_Use_Bean > ();
        try {
            String url = "https://graph.facebook.com/v2.12/me/posts?access_token=" + access_token;
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            // optional default is GET
            con.setRequestMethod("GET");
            //add request header
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in .readLine()) != null) {
                response.append(inputLine);
            } in .close();
            System.out.println(response);
            JSONObject data_response = new JSONObject(response.toString());
            JSONArray data_array = data_response.getJSONArray("data");
            System.out.println(data_array.length());
            for (int count = 0; count < data_array.length(); count++) {
                Post_Use_Bean obj_Post_Use_Bean = new Post_Use_Bean();
                obj_Post_Use_Bean.setId(data_array.getJSONObject(count).getString("id"));
                obj_Post_Use_Bean.setCreated_time(data_array.getJSONObject(count).getString("created_time"));
                try {
                    obj_Post_Use_Bean.setStory(data_array.getJSONObject(count).getString("story"));
                } catch (Exception e) {
                    System.out.println(e);
                }
                try {
                    obj_Post_Use_Bean.setMessage(data_array.getJSONObject(count).getString("message"));
                } catch (Exception e) {
                    System.out.println(e);
                }
                list_posts.add(obj_Post_Use_Bean);
            }
            JSONObject data_paging = new JSONObject(data_response.getJSONObject("paging"));
            Post_Use_Bean obj_Post_Use_Bean = new Post_Use_Bean();
            obj_Post_Use_Bean.setPaging_next(data_paging.getString("next"));
            obj_Post_Use_Bean.setPaging_previous(data_paging.getString("previous"));
            list_posts.add(obj_Post_Use_Bean);
        } catch (Exception e) {
            System.out.println(e);
        }
        //return list_posts;
	return list_posts;
    }
}

8. Post_Use_Bean.java


package com.chillyfacts.com.posts;
public class Post_Use_Bean {
	private String message;
	private String story;
	private String created_time;
	private String id;
	private String paging_previous;
	private String paging_next;
	public String getPaging_previous() {
		return paging_previous;
	}
	public void setPaging_previous(String paging_previous) {
		this.paging_previous = paging_previous;
	}
	public String getPaging_next() {
		return paging_next;
	}
	public void setPaging_next(String paging_next) {
		this.paging_next = paging_next;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getStory() {
		return story;
	}
	public void setStory(String story) {
		this.story = story;
	}
	public String getCreated_time() {
		return created_time;
	}
	public void setCreated_time(String created_time) {
		this.created_time = created_time;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
}

9. Profile_Modal.java


package com.chillyfacts.com.profile;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class Profile_Modal {
	public Profile_Bean call_me(String access_token) throws Exception {
	    String url = "https://graph.facebook.com/v2.12/me?fields=id,name,picture,email&access_token="+access_token;
	     URL obj = new URL(url);
	     HttpURLConnection con = (HttpURLConnection) obj.openConnection();
	     // optional default is GET
	     con.setRequestMethod("GET");
	     //add request header
	     con.setRequestProperty("User-Agent", "Mozilla/5.0");
	     int responseCode = con.getResponseCode();
	     System.out.println("\nSending 'GET' request to URL : " + url);
	     System.out.println("Response Code : " + responseCode);
	     BufferedReader in = new BufferedReader(
	             new InputStreamReader(con.getInputStream()));
	     String inputLine;
	     StringBuffer response = new StringBuffer();
	     while ((inputLine = in.readLine()) != null) {
	     	response.append(inputLine);
	     }
	     in.close();
	     System.out.println(response);
	     Profile_Bean obj_Profile_Bean=new Profile_Bean();
	     JSONObject myResponse = new JSONObject(response.toString());
	     obj_Profile_Bean.setUser_name(myResponse.getString("name"));
	     obj_Profile_Bean.setId(myResponse.getString("id"));
	     obj_Profile_Bean.setEmail(myResponse.getString("email"));
	     JSONObject picture_reponse=myResponse.getJSONObject("picture");
	     JSONObject data_response=picture_reponse.getJSONObject("data");
	     System.out.println("URL : "+data_response.getString("url"));
	     obj_Profile_Bean.setProfile_picture(data_response.getString("url"));
		return obj_Profile_Bean;
	   }
}

10. Login Page.
http://localhost:8080/FB_LOGIN_PROJECT/index.jsp


11. Login PopUP

12. Profile Page
http://localhost:8080/FB_LOGIN_PROJECT/Profile_Page.jsp

13. User facebook posts.

14. Download the project here.

FB_LOGIN_PROJECT.rar