Skip to content

Instantly share code, notes, and snippets.

@jkcgs
Last active December 18, 2015 04:39
Show Gist options
  • Save jkcgs/5726867 to your computer and use it in GitHub Desktop.
Save jkcgs/5726867 to your computer and use it in GitHub Desktop.
Obtener un post de una página de Facebook
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONTokener;
public class Test {
static String appId = "[APP_ID_HERE]",
appSecret = "[APP_SECRET_HERE]",
pageId = "[PAGE_ID_HERE]",
token, targetURL = "https://graph.facebook.com/%s/posts?fields=message,type&limit=1&";
public static void main(String[] args) {
String[] post = getLastFBPost();
if(post != null){
System.out.println(post[0]);
}
}
public static String[] getLastFBPost() {
String[] result = new String[3];
try {
// Get authorization token
token = getFacebookToken(appId, appSecret);
if(token == null){
System.out.println("Failed retrieving token");
return null;
}
// Create connection
URL url = new URL(String.format(targetURL, pageId) + token);
JSONObject root = (new JSONObject(new JSONTokener(url.openStream()))).getJSONArray("data").getJSONObject(0);
result[0] = root.getString("message");
result[1] = root.getString("type");
result[2] = root.getString("created_time");
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getFacebookToken(String appId, String appSecret){
String token;
HttpURLConnection connection = null;
try {
// Create connection
URL url = new URL("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" + appSecret + "&grant_type=client_credentials");
connection = (HttpURLConnection) url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
token = sb.toString();
} catch(Exception e) {
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
return token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment