Using Facebook API to fetch all Facebook posts of a user

Recently I had launched a website Your Facebook History in which you can dig into your Facebook history and see all the posts you have made on Facebook till now. The core logic for this website was to fetch all the Facebook posts of the user using Facebook API. So here is the code for this logic. It assumes you have already got the access token of user via Facebook oauth login.

Facebook puts limit on number of posts you can fetch with a single call, that is way this code recursively keeps on invoking Facebook API untill no more posts are left

private static void fetchPosts(HttpServletRequest req,
			List<JsonObject> msgs, String until, String nexttoken) {
 
		FacebookClient client = new DefaultFacebookclient(ACCESS_TOKEN)
		JsonObject api = null;
 
		if (until.length() == 0)
			api = client
					.fetchObject(
							"me/posts",
							JsonObject.class,
							Parameter.with("limit", "2000"),
							Parameter
									.with("fields",
											"type,story,message,created_time,likes.summary(true).limit(1)"));
		else
			api = client
					.fetchObject(
							"me/posts",
							JsonObject.class,
							Parameter.with("limit", "2000"),
							Parameter.with("until", until),
							Parameter.with("__paging_token", nexttoken),
							Parameter
									.with("fields",
											"type,story,message,created_time,likes.summary(true).limit(1)"));
		JsonArray data = api.getJsonArray("data");
		if (data == null || data.length() == 0)
			return;
		String next = api.getJsonObject("paging").getString("next");
		String[] nextsplit = next.split("&");
		for (String s : nextsplit) {
			if (s.contains("until"))
				until = s.split("=")[1];
			if (s.contains("__paging_token"))
				nexttoken = s.split("=")[1];
		}
		for (int x = 0; x < data.length(); x++) {
			JsonObject jobj = data.getJsonObject(x);
			try {
				String type = jobj.getString("type").toLowerCase();
 
				if (type.equalsIgnoreCase("status")) {
					msgs.add(jobj);
					try {
						if (jobj.has("likes")) {
							int likes = jobj.getJsonObject("likes")
									.getJsonObject("summary")
									.getInt("total_count");
							jobj.put("likes", likes);
						} else
							jobj.put("likes", 0);
					} catch (Throwable tt) {
						jobj.put("likes", 0);
					}
				}
			} catch (Exception e) {
				System.out.println(e);
			}
		}
		if (data.length() > 0)
			fetchPosts(req, msgs, until, nexttoken);
 
	}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *