Facebook Java api example to publish on Wall

According to facebook Wiki posting on a  wall is very confusing and very difficult to write a program to publish on a wall. And it Don’t even support or document any methods on how to publish on wall using JAVA, and thanks to Google for giving a JAVA library to post on facebook.

Download Library from http://code.google.com/p/facebookjavaapi/

Don’t confuse and don’t use old libraries only use facebook-java-api-3.0.1-bin.zip or greater.

I spent around 2 weeks reading many articles and many documents, Wiki on facebook but in vein and tried many ways and finally I got one workable model. Below are simple steps to publish on a Facebook wall using JAVA.

Step1: Login to Facebook

First login to Facebook and goto the url http://www.facebook.com/developers/ then

Click on “+ Set Up New Application” button to start creating the application as shown below.

start application

Provide the application name, click agree for facebook terms and click on “Create Application” button.

Fill in application Name

create app step1

Now Application is created for you. Just copy the Application API Key, Application Secret and Application ID details which will be used to write the application code.

application page

Now goto Canvas link and enter any url.

canvaspage

Next goto Connect URL link and enter the same url.

connecturl

Then click on Save. That’s it we have created a facebook application with an Iframe.

Now Copy Application API Key, Application Secret and Application ID details which will be used to write the application code.

Now download the php library from facebook “http://blog.theunical.com/wp-content/uploads/2010/05/facebook-platform.tar1.gz”. For now we will use this library for generating one time session key.

Step2: Generate One Time Token key

How to generate One Time Token key:

Run below URL to get temporary token for the particular user by logging into Facebook.

https://login.facebook.com/code_gen.php?api_key=API_KEY&v=1.0

Note: Please replace “API_KEY” with your application API key from above page.

Then we will get a temporary token key.

allowaccess

generatemylogin info

savemyinfo

This is one time token key that we can use to generate a permanent session key. Careful! Don’t try to execute this programs many times

Step3: Generate one time session key

Below is the sample JAVA code to generate one time session key.

/**
 * FacebookClient
 *
 */
public class FacebookClient {
 public static String API_KEY = “YOUR API KEY”;
 public static String SECRET = “YOUR SECRET”;
 public static void main(String args[]) {
 // Create the client instance
 FacebookRestClient client =       new FacebookRestClient(API_KEY, SECRET);
 client.setIsDesktop(true); // is this a desktop app

 try {
 String token = client.auth_createToken();
 // Build the authentication URL for the user to fill out
 String url = “http://www.facebook.com/login.php?api_key=”
 + API_KEY + “&v=1.0″
 + “&auth_token=” + token;
 // Open an external browser to login to your application
 Runtime.getRuntime().exec(“open ” + url); // OS X only!
 // Wait until the login process is completed
 System.out.println(“Use browser to login then press return”);
 System.in.read();

 // fetch session key
 String session = client.auth_getSession(token,true );
// obtain temp secret
String tempSecret = client.getSessionSecret();
// new facebook client object
client = new FacebookJaxbRestClient(API_KEY, tempSecret, sessionKey);

 System.out.println(“Session key is ” + session);

 // keep track of the logged in user id
 Long userId = client.users_getLoggedInUser();
 System.out.println(“Fetching friends for user ” + userId);

 // Get friends list
 client.friends_get();
 FriendsGetResponse response = (FriendsGetResponse) client.getResponsePOJO();
 List<Long> friends = response.getUid();

 // Go fetch the information for the user list of user ids
client.users_getInfo(friends, EnumSet.of(ProfileField.NAME));

UsersGetInfoResponse userResponse = (UsersGetInfoResponse) client.getRepsonsePOJO();
 // Print out the user information
 List<User> users = userResponse.getUser();
 for (User user : users) {
 System.out.println(user.getName());
 }
 } catch (FacebookException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
}

(OR)

For example, the full URL for logging in a user could be:

http://www.facebook.com/login.php?api_key=YOURAPIKEY&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access

If the user is redirected to the URL specified by the next parameter, then Facebook grants your application a session. This session is appended to the URL as a JSON-decodable object of the form:

&session={“session_key”:”SESSIONKEY”, “uid”:USERID, “expires”:0 || UNIXTIME, “secret”:”SESSIONSECRET”}

In continuing with the above example, the redirect for a successful login would be:

http://www.facebook.com/connect/login_success.html?session=%7B%22session_key%22%3A%223.kxhAu6W0qo_bLGjmdWrgfw__.86400.1243443600-688626964%22%2C%22uid%22%3A%22688626964%22%2C%22expires%22%3A1243443600%2C%22secret%22%3A%220NVNMxpO6jVyDcVCvVv_PA__%22%2C%22sig%22%3A%22ac1c0c77c137567389defea70481b7aa%22%7D

If the user grants your application the offline_access extended permission, 0 gets returned for expires and the session never expires unless the user removes the application. In this case, you should store the session key so the user doesn’t have to log in the next time he or she launches your application.

Once the browser has been redirected successfully and you have your session information, you should automatically close the browser window.
Note: The above code will execute only once. We should note down the above session key, This will be used to auto login into the application.

Note: The above code will execute only once. We should note down the above session key, This will be used to auto login into the application.

If you don’t save these session key values you should generate other token key to create one time session key.

We can use the token only once.

Step4: Setting Permission for wall

Giving Permission to your application to publish on facebook wall. To give permission just replace the your API key in below URL and execute in browser.

http://www.facebook.com/login.php?api_key=APIKEYXxxxxxxxxxxxxxxxxx&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&req_perms=read_stream,publish_stream,offline_access

Then you must see the below 3 Screens

If you don’t see the below then your call back URL or Canvas URL must be incorrect, please check again your application settings and execute the URL again.

allowpermission

allowpublishing

Then on final page, you will see a success message.  That’s it you have given permission for read_stream,publish_stream and offline_access.

Step5: Publishing the message on Facebook Wall

Java Code to create facebook object with onetime session key and publishing the message on Facebook Wall.

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import com.google.code.facebookapi.Attachment;
import com.google.code.facebookapi.AttachmentMediaImage;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.FeedFacebookPhoto;
import com.google.code.facebookapi.Permission;
import com.google.code.facebookapi.TemplatizedAction;

public class SendtoFacebook {

	public static void main (String a[]) throws FacebookException{ 

	SendtoFacebook sfb=new SendtoFacebook();
	sfb.send("From My App: publish steven on facebook");
	}
	public void send(String message)throws FacebookException{

		String FB_APP_API_KEY = new String("YOUR_APIKEY");
		String FB_APP_SECRET = new String("YOUR_SECRET");
		String FB_SESSION_KEY = new String("YOUR_ONETIMESESSIONKEY");
		FacebookJsonRestClient facebook = new FacebookJsonRestClient( FB_APP_API_KEY, FB_APP_SECRET, FB_SESSION_KEY );

		//FacebookJsonRestClient facebookClient2 = (FacebookJsonRestClient)facebook.getFacebookRestClient();
		FacebookJsonRestClient facebookClient = (FacebookJsonRestClient)facebook;
facebookClient.stream_publish(message, null, null, null, null);

			System.out.println("successfully updated");

	}
}

Now you will see the post on wall Great.

published on facebook

So thrilling isn’t we can also publish photos videos on wall.

http://wiki.developers.facebook.com/index.php/Stream.publish

have a great day

– Steven

Steven Fan Page on Facebook

Please don’t copy this content to any site. This is fully protected by TheUnical Technologies

79 thoughts on “Facebook Java api example to publish on Wall”

  1. Hi,
    i tried your example, This works well, but when i am trying to publish on page (i am admin to the page not Fan ), All Messages are showing Under Fan’s category, but what i need is, the message should be posted under User/page category.

    Can u share any ideas or even Links,

  2. Thanks for the article! It has cleared some of my doubts on using the Java API 🙂
    I have a few queries:
    1. Is the session key generated at the end of step 3 the same being used in the JAVA program in step 5?
    2. Can the program in step 5 be used N number of times to post updates on the wall?
    3. Can the session key generated above for user, lets say A, be used to post on the wall of another user B?
    4. Is there any way to post onto the wall of a user without logging in always?

  3. Good to hear Faz,
    Here are my answers
    1. Is the session key generated at the end of step 3 the same being used in the JAVA program in step 5?
    Yes

    2. Can the program in step 5 be used N number of times to post updates on the wall?
    Yes, we can use this any number of times, if we can error at anytime then we need to generate a new key.

    3. Can the session key generated above for user, lets say A, be used to post on the wall of another user B?
    If you give access then it is possible, but you need to change the target userid to post it on User B.

    4. Is there any way to post onto the wall of a user without logging in always?
    This 5 five steps if you execute without any bugs then you need not login to publish.
    You just have to execute Step5 always to publish without login. once you give authentication there is no need to login.

  4. Hey

    I have tried following the steps but the code in step 3 does not work for me. I am using netbeans and do I need any other imports apart from facebook 3.2 api?

    Thanks in advanced.

    Edward

  5. Hello Edward I have added one more simple way to do this. Just execute the above URL in step3 to generate Session key.

  6. Hey Steven,
    Thanks for the examples.
    I did something a bit different so far so I was wondering if you could help me continue.
    I’ve used javascript to get extended permissions from the user and it works (if I check the users application settings, my application is there). So basically what I need to do is post to the user’s feed.
    At which stage from the ones you wrote above should I start?
    Thank you!

  7. Hello there , i’m developping an api facebook interface , and actually i’m stuck in a rut !!!!
    i’ve searched for source code all over the net web , i finally found a nice one , here it is , below ( but before seing it ) I HAVE A PROBLEM WITH CLIENT.ISSETDESKTOP(TRUE) IT DOESNT WOOOOORK , please help , here is the code guys :

    import java.io.IOException;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.HttpState;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpClientParams;
    import com.google.code.facebookapi.FacebookException;
    import com.google.code.facebookapi.FacebookXmlRestClient;

    public class Login {
    public static String login(String API_KEY, String SECRET_KEY, final String email, final String password) throws FacebookException, HttpException, IOException { //LOGIN (finally got this one working 🙂 )

    //Creating an HttpClient instance used for requesting (GET and POST) to login
    //The HttpClient should only be used for the login system
    HttpClient http = new HttpClient(); //The host will be offcourse http://www.facebook.com
    http.getHostConfiguration().setHost(“www.facebook.com”);

    //Creating the client based on the public API_KEY and the private SECRET_KEY
    FacebookXmlRestClient client = new FacebookXmlRestClient(API_KEY, SECRET_KEY);
    //Is this application a desktop application?
    // TODO Check what the meaning of “isDesktop” exactly is (is mobile application a desktop application?)
    //When false the friendlist cannot be obtained :/
    //client.setIsDesktop(false);

    //Create the authentication token
    String token = client.auth_createToken();
    System.out.println(“LOGIN – Authentication Token created upon login: ” + token);

    //Setting for the HttpClient instance
    HttpClientParams params = new HttpClientParams();
    HttpState initialState = new HttpState();
    http.setParams(params);
    http.setState(initialState);

    //Getting the login page specific for this application
    //Basically this will not change with a newer facebook version
    GetMethod get = new GetMethod(“/login.php?api_key=” + API_KEY + “&v=1.0&auth_token=” + token);

    //Request the login page from the World Wide Web
    int getStatus = http.executeMethod(get);
    System.out.println(“LOGIN – Http status returned when executing GET: ” + getStatus);

    //Setting up POST method to actually do the login work
    PostMethod post = new PostMethod(“/login.php?login_attempt=1”);
    //Set the needed login parameters. These are the html elements on the
    //applications login screen, requested with the GET-method, that
    //will be submitted on login (“version” used to be “v” in old facebook)
    post.addParameter(“api_key”, API_KEY);
    post.addParameter(“version”, “1.0”);
    post.addParameter(“auth_token”, token);
    post.addParameter(“email”, email);
    post.addParameter(“pass”, password);

    //Do the actually login on the World Wide Web
    int postStatus = http.executeMethod(post);
    System.out.println(“LOGIN – Http status returned when executing POST: ” + postStatus);

    //Get the authentication session string, needed in the rest of the application
    String session = client.auth_getSession(token);
    System.out.println(“LOGIN – The Authentication Session string: ” + session);

    //Request the userid of the currently logged in user, will be
    //needed further on the application
    long userid = client.users_getLoggedInUser();
    System.out.println(“LOGIN – Successfull login for user with id ‘” + userid + “‘”);

    return session; } }

  8. hie..first of all, thank you for sharing this great & helpful code.
    I have tried running the FacebookClient.java on eclipse.
    I did get the session and tempSecret printed out. 🙂
    However, i still couldn’t retrieve the user’s information and other as coded in the code above.
    Instead, it return me an error message as below:
    Incorrect signature
    at com.google.code.facebookapi.FacebookJaxbRestClientBase.parseCallResult(FacebookJaxbRestClientBase.java:181)
    at com.google.code.facebookapi.FacebookJaxbRestClient.friends_getLists(FacebookJaxbRestClient.java:533)
    at FacebookClient.main(FacebookClient.java:46)

    Can you please explain to me regarding this error.
    And what can i do to retrieve and printout the relevant information on the console.
    Need help badly.
    Thank you so much.

  9. Hi Steven, I got it now since i’ve change the setting to my application 🙂
    Thank you again..
    from the FacebookJaxbRestClient client object, can i also retrieve groups?
    it seems complicated to me. can you help me with this?
    thank u so much

  10. I have a java site that uses FacebookJsonRestClient, I get a list of the users friends and would like to send an invite to some of the friends. Can anyone help me on how to do this?
    FacebookJsonRestClient.notifications_send has been deprecated, how can I send an invite or a message to a friend?

    soph

  11. Good morning Steven. Thank You for a great article. I have a question when I resolve the permission link http://www.facebook.com/login.php?api_key=APIKEYXxxxxxxxxxxxxxxxxx&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&req_perms=read_stream,publish_stream,offline_access

    I see success message but how can I redirect my user into my facebook application. My application is in iFrame and when I put http://apps….. facebook write to me that I should configure connect page, and when I try to change it, that don’t helps. How can I redirect browser into my application in iFrame?

  12. So on step 3 you are supposed to take your API key and insert it into the URL, correct? And from there you are supposed to get a session key in return? I am confused because the code in step 3 did not work so I tried the URL step but I just got the “Success” in return. Im also wondering in step 2 what I use that token key for because in the URL step I do not see how it gets used.

    So my question is in Step 3 am I supposed to get something in return and my other question is what do I end up doing with my one-time token key in step 2.

    Also, in the step 5 code you have this line “String FB_SESSION_KEY = new String(“YOUR_ONETIMESESSIONKEY”);”, Is that ONETIMESESSIONKEY supposed to be the key you get in return from step 3? If you could clarify these things for me that would be great because I am getting an error in my program saying

    “Exception in thread “main” com.google.code.facebookapi.FacebookException: Session key invalid or no longer valid
    at com.google.code.facebookapi.JsonHelper.parseCallResult(JsonHelper.java:59)
    at com.google.code.facebookapi.ExtensibleClient.extractString(ExtensibleClient.java:2296)
    at com.google.code.facebookapi.ExtensibleClient.stream_publish(ExtensibleClient.java:2150)
    at com.google.code.facebookapi.SpecificReturnTypeAdapter.stream_publish(SpecificReturnTypeAdapter.java:503)
    at SendtoFacebook.send(SendtoFacebook.java:35)
    at SendtoFacebook.main(SendtoFacebook.java:21)”

    Thanks in advance,
    Matt

  13. Yes Matt, In Step2 you will get a token which you will use in Step3 php code to get permanent session key, this will be used to publish on facebook without login to FB.

  14. Hello Steven,

    Trying to follow your example, I noticed that the download link “http://svn.facebook.com/svnroot/platform/clients/packages/facebook-platform.tar.gz” is no more functional.

    Could you provide this archive, or an updated download link?

    Many thanks,
    Manu

  15. In step3, Generate one time session key, you use class FacebookRestClient but I can not find out it in API for this class after downloading facebook-java-api-3.0.2-bin.zip from code.google.com. The code snippet is not including import section. Can you specify it?

  16. getting below error, when trying to execute the above code…..
    com.google.code.facebookapi.FacebookException: Incorrect signature

  17. hi…..steven..
    it works…..thanks……alot
    but the….. can’t we write some others wall…….if so what should be done

  18. bcoz…..im doing a java project for my 2nd year, automated system for a mobile shop.
    so i thought of giving messages to customers facebook account.
    if u have any idea or advise ……..ur welcome…

  19. help me please:

    After i got the session key, i copy n paste to the step5 which into the

    String FB_SESSION_KEY = new String(“XXXXXX”);

    and i got this error eventhough this is the first time.
    ————————————————————————————————-

    Exception in thread “main” com.google.code.facebookapi.FacebookException: Session key invalid or no longer valid
    at com.google.code.facebookapi.JsonHelper.parseCallResult(JsonHelper.java:59).

    ——————————————————————————————————-

  20. hi guys…. thanks i got the answer already…

    and thank so much ur page very helpul….

    Thanks & Regards,
    Meelo =p

  21. This is a great article. But I am getting problem in step 5 importing org.apache.commons.httpclient.* . Do I need to download any specific JRE or package for that purpose as org.apache.commons is not in the system JRE.

    Eagerly wating for that part to be solved. Also I would like to know if there is any method to send the post to other users wall.

    Thanks for replying.

  22. Hi Steven ,

    This will perhaps not take much of your time.
    I am stuck at step2.
    I downloaded facebook-platform.tar1.gz and unzipped.
    So What exactly I should be doing now?
    I don’t know php at all.
    Am I to put the url with my app_key in a php and open it in browser?

    Please guide.
    Thanks.

  23. Hi Steven,

    Thanks for your reply, currently I am using jdk1.6.0
    Could you please specify a bit more what lib should I download as the purpose is not solved yet, and what would be the source for that? Do I need to make any special inclusion after the download (like external jar) or any change in the classpath?

    Looking forward to your reply.

    Thanks once again.

  24. Hi,

    In case there is someone having problem like mine, the lib org.apache.commons.httpclient can be downloaded from http://www.java2s.com/Code/Jar/ABC/Downloadcommonshttpclient301jar.htm and included trough the IDE as a external JAR.

    So the previous problem was fixed, but the thing is I didnt get anything posted on the facebook wall. does it take time to get the post or should I try and repeat the whole procedure once again to get new app key token key and session key?

    Please advise. Thanks.

  25. Hi Steven,

    I think you didn’t get my question.
    I have not been able to generate the token key.
    In step2 (Generate One Time Token key) what exactly am I to do?

    When I go to https://login.facebook.com/code_gen.php?api_key=API_KEY&v=1.0
    (replacing API_KEY with my valid key) I get an error:
    An error occurred with ‘My_App’. Please try again later.
    API Error Code: 100
    API Error Description: Invalid parameter
    Error Message: Requires valid next URL.

    At the end of step 1 you have mentioned I should download the php library. Am I to use it to generate this one time token key in second step?

    Sorry if this is wasting your time.
    But please guide.

    Thanks.

  26. Hi,

    Please help me in generating Access_token using java code. I don’t need any window prompt or any thing else.

    please help

    Regards
    jagdeep

  27. Hello Steven,
    First of all, many thanks for this article, it helped me a lot to connect with Facebook. I have a problem though…
    I am developing a desktop application and I want to be able to post on the authenticated user’s wall, or on a group/page that user is part of/likes. Also, the post must contain a picture which is saved locally, on the hard-drive. As I’ve seen on the Graph API docs, a post has a picture attribute, so normally I should be able to specify the path to the picture I want to upload. The problem is this doesn’t seem to work and I don’t know why. Is it not possible to specify a local path to the image (e.g “C:/picture.png”) ?

  28. Isn’t there an alternative for doing this? For example, if I want to upload a photo to a user’s wall, I can use the photos_upload method from the Facebook Java API, but I won’t be able to use this method if I want to upload the photo on a group’s or page’s wall, so I though of using the stream_publish method instead, which gave me the problem I mentioned in my first post.

  29. Hi,
    I have been trying to develop a facebook app on php.Though the code is working fine I haven’t been able to publish on the users wall.Do we need the javascript SDK for doing that.I tried going through your post but couldn’t understand the following
    1.How do we redirect the user to this link,as given in step 1 of the post
    https://login.facebook.com/code_gen.php?api_key=API_KEY&v=1.0
    2.Where is the one time token key stored,as given in step 2 of the post

    Pls help me,I am still an amateur programmer

  30. @Aks you don’t need any javascript to do above step1, you only need any of java /php libraries to make it work. The one time session key will not be stored it will display in browser u need to save it in your program

  31. Hi,
    Thanks for this lovely article. This article is very help full for me and i am able to post on user wall text as well as image but my problem in step 3 calling URL from browser its working but i want to fetch the user offline session-id from my web page using this URL how can i achieved this or any alternate way is there for getting user offline session-id?

    Please help me.

    Thanks allot.

  32. Hi,
    I want to make a standalone java application where on passing the username and password of a particular user of facebook, would allow the app to post simple text (maybe a link too) to the user’s wall.
    If you can help me in this regard it would be of great help.

  33. @Steven: great article!

    Have a question for you. Please pardon my naivette, I’m new to facebook app development. What is the purpose of a “one time token key” in Step 2, and a “one time session key” in Step 3?

    The following URL says that if our facebook client app is really running on our server, it’s ok to simply send Facebook servers the secret key, i.e., there is no need for a one-time session key for the case when isDesktop is false: http://code.google.com/p/facebook-java-api/wiki/DesktopMode

    Thanks for your response.

Leave a Reply

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

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image