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 have created one apps which create a new pic in a new album. Now i want to publish this new pic on wall. Can u please help me how to do it ??

    thanks in advance. 🙂

  2. Hi thanks a lot in advance the code works perfectly for me.But the problem is it updates the status on my wall which is a user account but instead I want it to update in the wall of the app.

  3. Hi Developers. Do you know how to capture the “logout” event fired from facebook page? With that, I am able to logout the user from my app.
    I face the problem that, with the user hit the logout button (in the facebook account) the user still is registered from my app.
    How do you resolve that?
    Tnx

  4. Hi Steven and rest all,
    I am very new to Java and Facebook app development, was referring this blog for creating a Java application with Facebook integration.
    Please refer “Point1” and “Point2”, as marked in the code below. and suggest whether replacing “FacebookRestClient” with “FacebookJaxbRestClient” is correct or not, as mentioned in Point1. And client.setIsDesktop(true); is giving an error, as mentioned in Point2.

    import java.io.IOException;
    import java.util.EnumSet;
    import java.util.List;
    import com.google.code.facebookapi.FacebookException;
    import com.google.code.facebookapi.FacebookJaxbRestClient;
    import com.google.code.facebookapi.ProfileField;
    import com.google.code.facebookapi.schema.FriendsGetResponse;
    import com.google.code.facebookapi.schema.User;
    import com.google.code.facebookapi.schema.UsersGetInfoResponse;

    public class Facebook {
    public static String API_KEY = “*****”;
    public static String SECRET = “******”;
    private void creatingSessionKey()
    {
    //Point1: Replace “FacebookRestClient” with “FacebookJaxbRestClient” as “FacebookRestClient” is no more supported in “facebook-java-api-3.0.2”. Please verify that doing this is right
    //FacebookRestClient client = new FacebookRestClient(API_KEY, SECRET);
    FacebookJaxbRestClient client = new FacebookJaxbRestClient(API_KEY, SECRET);

    //Point2: The line below, giving an error Message “The method setIsDesktop(boolean) is undefined for the type FacebookJaxbRestClient”
    //client.setIsDesktop(true); // is this a desktop app
    try {
    //String token = client.auth_createToken();
    String token = “U7H8GF”;

    String url = “http://www.facebook.com/login.php?api_key=”
    + API_KEY + “&v=1.0”
    + “&auth_token=”+ token;
    System.out.println(url);
    // 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.getSecret();
    // new facebook client object
    client = new FacebookJaxbRestClient(API_KEY, tempSecret,session);
    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 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.getResponsePOJO();
    client.getResponsePOJO();
    // Print out the user information
    List users = userResponse.getUser();
    for (User user : users) {
    System.out.println(user.getName());
    }
    } catch (FacebookException e) {
    System.err.println(“Error: ” + e.getMessage());
    e.printStackTrace();
    }catch (IOException e) {
    e.printStackTrace();
    }
    }

    public static void main(String args[]) {
    new Facebook().creatingSessionKey();

    }
    }

    Also on running this program, is giving an Connection timed out error, how can it be solved, is it through raising timeout duration, if yes than how to raise timeout duration here. The Error message is :

    Exception in thread “main” java.lang.RuntimeException: java.net.ConnectException: Connection timed out: connect
    at com.google.code.facebookapi.BasicClientHelper.runtimeException(BasicClientHelper.java:123)
    at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:538)
    at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:446)
    at com.google.code.facebookapi.ExtensibleClient.auth_createToken(ExtensibleClient.java:860)
    at com.google.code.facebookapi.SpecificReturnTypeAdapter.auth_createToken(SpecificReturnTypeAdapter.java:73)
    at Facebook.creatingSessionKey(Facebook.java:27)
    at Facebook.main(Facebook.java:74)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
    at com.google.code.facebookapi.ExtensibleClient.postRequest(ExtensibleClient.java:583)
    at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:534)
    … 5 more

  5. I want to post on wall of a facebook page and not the profile. I am using the code posted above to post on profile but I can’t use the code to post on page associated with the profile. I am changing the page id associated with the page but still it doesn’t work. Please help.

  6. Hi,
    i want to post face book wall using java.I was trying this example .i have got the sessionkey using that link.and when i pass that session id in step 5 it shows the exception as below :

    com.google.code.facebookapi.FacebookException: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons.

    im trying to achieve this task more that 10 days …please help me 🙁

  7. @Sathya its not problem with code it with key u are generating, r u logging in to the same account with same login details or login as a developer?
    try to login as the admin / main user not Developer login , then generate key.

  8. Hi all,
    Im trying to publish a video using stream_publish from FacebookJsonRestClient in java.

    The issue here is my youtube video is being posted to the facebook Page, but the video is not playing. Its showing empty. When i right click the video, it says Media Not Loaded.

    Why is it so?
    My code goes like this:

    FacebookJsonRestClient facebook = new FacebookJsonRestClient(
    apiKey, appSecret, sessionKey);
    FacebookJsonRestClient facebookClient = (FacebookJsonRestClient) facebook;
    System.out.println(“11”);

    Attachment attachment = new Attachment();
    attachment.setName(“Test attachment”);
    attachment.setHref(“http://www.youtube.com/watch?v=jcuihSvspt4”);
    attachment.setCaption(“The attachment object holds stuff.”);
    attachment.setDescription(“This is a test attachment object.”);
    System.out.println(“done with attachment”);

    AttachmentMediaVideo mediaVideo = new AttachmentMediaVideo(
    “http://www.youtube.com/watch?v=jcuihSvspt4”,
    “http://icanhascheezburger.files.wordpress.com/2009/04/funny-pictures-hairless-cat-phones-home.jpg”,
    “kitty”, “application/x-shockwave-flash”,
    “http://www.youtube.com/watch?v=jcuihSvspt4”);
    attachment.setMedia(mediaVideo);
    System.out.println(“done with mediavideo”);

    String message = “Facebook stream publish video test.”;
    facebookClient.stream_publish(message, attachment, null, null,
    pageId);

  9. Hi all, I am getting below exception when i run the application to post on wall. And in current developer site, i am not finding \”connect URL\” field, please let me know where to add connect url setting in current developer site?
    xception in thread \”main\” java.lang.RuntimeException: java.net.ConnectException: Connection refused: connect
    at com.google.code.facebookapi.BasicClientHelper.runtimeException(BasicClientHelper.java:123)
    at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:538)
    at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:460)

  10. My First app is a simple 3 html page program
    1) A simple html landing page with a button asking the user to go to app. This click opens OAuth popup and registers user…I have used a simple dialog oauth redirect. I am also getting the reponse type as access token.
    2) A simple form with options to select and submit to see the result
    3) Result.htm page showing an image.

    My prob is how to use the access token on page 2 or shud I reload the JS sdk for fb on this page as well, tho I am nt doing anything with it there but I surely need the token on page 3 as I want to tag and upload the image on user’s profile.

    Can anybody help me with it. I would appreciate some steps I need to follow and a piece of code.
    P.S I am trying to to this using javascript..no php no jsp jst simple html and javascript.

    Sandy

  11. I tried to follow the instruction in the post but the layout of new FB Apps is different and i cant find API KEY
    i have only:
    App ID
    App Secret:

    may be i am not in the right FB apps Place? or somethins else

    thank you in advance

  12. Hi Pietro,

    For your info,

    App ID and API key are the same. As long as you any 1 of these, you can proceed with the next step.

  13. Hi all, i noticed that now facebook is using OAUTH 2.0 to pass thru the authorization, where i can see the oauth wording in their URL itself.

    ex: https://www.facebook.com/dialog/oauth?
    client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream

    While in this blog, its showing old way of accessing facebook apps (since facebook always changing..), but using JAVA (which is cool!).

    Now my question is…
    does this old way of calling facebook app is also using OAUTH or some other authorization method??

    please explain…thanks in adnvanced..

  14. Hi Steven, thanks for the code snippet. And thanks to all for yours comment that help me a lots to solving some problems that i am facing while running this code. Now it works well……………

    But I have some problem regarding this. I want to post on multiple user’s wall. But now i only able to post on my profile which app key and secret key were passed in this code.

    If any one having some idea related with this, then plz share with me.

    Thanks in adnvanced..

  15. Hi, i am searching the solution that how to give authorization to my facebook app to post on other’s wall.

  16. I have followed your program but I am facing an issue in Step 3 at line 14.

    String token = client.auth_createToken();

    The error which I am getting is “Incorrect signature”

    Please give my any clue.

  17. Hi Vara, i think u don’t set your application as desktop application. If not then go to the Apps page and select the Native/Desktop radio button for yr application.

  18. Thankzz Man.. This URL served My purpose.. Now im comfortably building my app in java.. !!!!

  19. Hi guys,
    now my application is working good. But i have a issue on step-3 that instead of the window ” You may now close this window and return to the application. ” i want to open any page from my application.

    Is it possible? If yes, please give me the details about that.

  20. Hi ,
    I already add the offline_access permission still my facebook session key is expired after 1 day. How to solve this problem.

    Any one have some idea about that plz help me.

  21. hiii

    The method getSessionSecret() is undefined for the type FacebookRestClient

    please help me i add facebook-java.api1.7 jar but found error please help me..

  22. Hi …
    I am new in java…..could u plz give the proper code of .How to login into my simple java application via facebook id…….really its urgent…give me code ASAP….
    Thanks in advance

  23. Hey hi, i copied step3 code in eclipse and run it as java application. Browser IE opened and login into the fb as well..but then after nothing is happening. I dont get session key n all after that.. I am new to java and fb..please help me….. 🙁

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