Posting photos to Facebook album using Graph API

28 / Jun / 2012 by Vishal Sahu 0 comments

Hi,
In my recent grails project, i needed to post images to the albums for Facebook Profile/ Fan page/ Group using facebook API. I searched a lot and find a way to achieve this using Facebook Graph API.


To post any content over facebook, we need to have facebook access_token which can be obtained using steps described here


After successfully obtaining access_token, we can easily use graph API to post message/photos to any album for that profile or page.
We need to have album_id to post photos to any album. If there is no album present, the it will create an album with the same name as of the Facebook App, which is posting the photos and put all the photos in that Album.


Make sure the access_token have publish_stream permission to post the content over facebook.


Code to post photos to facebook album is as :-


[java]

String access_token= ACCESS_TOKEN // access_token obtained from facebook
String message= MESSAGE // message to be published with photo.
String photo_url=PHOTO_URL // url of the photo to be published

StringBuilder sb = new StringBuilder("access_token=");
sb.append(URLEncoder.encode(token, "UTF-8"));
sb.append("&message=");
sb.append(URLEncoder.encode(message, "UTF-8"));
sb.append("&url=");
sb.append(URLEncoder.encode(photo_url, "UTF-8"));
String feedUrl = "https://graph.facebook.com/me/photos"
// use Album ID or FanPage ID in the feedURL instead of /me/ in case you want to publish photos to specific Album or Fan page

URL url = new URL(feedUrl);
HttpURLConnection connection
try {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("Content-Length", "" + sb.toString().length());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
outputStreamWriter.write(sb.toString());
outputStreamWriter.flush();
}
catch (Exception e) {
e.printStackTrace()
}

[/java]


This will post the provided image via url to the album mentioned in the API call.


This worked for me.
Hope it helps.


Useful Links:
http://developers.facebook.com/docs/reference/api/album/
http://www.tothenew.com/blog/integrate-java-application-with-facebook-using-graph-api/


Cheers!!!
Vishal Sahu
vishal@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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