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/facebook-java-api/
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.

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

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.

Now goto Canvas link and enter any url.

Next goto Connect URL link and enter the same url.

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.



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:
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:
In continuing with the above example, the redirect for a successful login would be:
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.


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.

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
Please don’t copy this content to any site. This is fully protected by TheUnical Technologies
Comments
79 Comments on Facebook Java api example to publish on Wall
-
kalyan on
Thu, 19th Nov 2009 7:58 am
-
lola on
Wed, 13th Jan 2010 6:01 pm
-
Steven Robert on
Thu, 14th Jan 2010 5:47 am
-
Faz on
Tue, 16th Feb 2010 3:31 am
-
Steven Robert on
Tue, 16th Feb 2010 11:01 pm
-
Edward Ireson on
Sat, 6th Mar 2010 5:17 pm
-
amarikanit on
Sun, 7th Mar 2010 3:43 pm
-
Steven Robert on
Sun, 7th Mar 2010 10:48 pm
-
Steven Robert on
Sun, 7th Mar 2010 11:01 pm
-
Edward Ireson on
Mon, 8th Mar 2010 2:18 pm
-
Dikla on
Thu, 18th Mar 2010 1:28 pm
-
Steven Robert on
Fri, 19th Mar 2010 4:27 am
-
Michael Moore on
Fri, 19th Mar 2010 6:46 am
-
Michael Moore on
Fri, 19th Mar 2010 6:48 am
-
Hassana on
Mon, 12th Apr 2010 4:51 am
-
Steven Robert on
Mon, 12th Apr 2010 6:44 am
-
Hassana on
Tue, 13th Apr 2010 5:19 am
-
sophia on
Sat, 24th Apr 2010 3:22 am
-
Boris on
Fri, 7th May 2010 10:54 am
-
Matt Gibson on
Tue, 11th May 2010 4:30 pm
-
Steven Robert on
Tue, 11th May 2010 11:33 pm
-
Steven Robert on
Tue, 11th May 2010 11:49 pm
-
Manu on
Wed, 12th May 2010 6:39 am
-
Steven Robert on
Thu, 13th May 2010 4:17 am
-
david on
Tue, 25th May 2010 4:33 pm
-
Devinka on
Tue, 15th Jun 2010 12:57 pm
-
kamarul on
Wed, 16th Jun 2010 12:37 am
-
shiva on
Mon, 19th Jul 2010 4:50 am
-
Haneef on
Sun, 25th Jul 2010 12:27 pm
-
Haneef on
Sun, 25th Jul 2010 12:42 pm
-
meelo on
Mon, 23rd Aug 2010 3:18 am
-
meelo on
Mon, 23rd Aug 2010 8:39 pm
-
Jita on
Tue, 31st Aug 2010 8:51 am
-
Prasi on
Tue, 31st Aug 2010 10:16 am
-
Steven Robert on
Tue, 31st Aug 2010 11:38 pm
-
Steven Robert on
Tue, 31st Aug 2010 11:40 pm
-
Jita on
Wed, 1st Sep 2010 2:16 am
-
Jita on
Wed, 1st Sep 2010 2:32 am
-
Prasi on
Wed, 1st Sep 2010 3:30 am
-
Steven Robert on
Wed, 1st Sep 2010 11:39 pm
-
Steven Robert on
Wed, 1st Sep 2010 11:41 pm
-
jagdeep on
Tue, 21st Sep 2010 11:32 am
-
Catalin on
Fri, 1st Oct 2010 9:19 am
-
Steven Robert on
Sat, 2nd Oct 2010 12:50 am
-
Catalin on
Mon, 4th Oct 2010 7:14 am
-
Aks! on
Wed, 6th Oct 2010 3:35 pm
-
Steven Robert on
Thu, 7th Oct 2010 11:18 pm
-
Sumit Singhal on
Thu, 14th Oct 2010 12:48 am
-
kiran bhushan on
Tue, 16th Nov 2010 8:34 am
-
bill on
Wed, 17th Nov 2010 2:47 am
-
somu on
Wed, 17th Nov 2010 5:56 pm
-
rohit on
Wed, 16th Feb 2011 3:35 pm
-
Steven Robert on
Wed, 16th Feb 2011 10:58 pm
-
Zarif on
Mon, 4th Apr 2011 10:35 am
-
Pedro Silva on
Sat, 14th May 2011 5:53 pm
-
Rituraj on
Mon, 16th May 2011 9:09 am
-
Sameer on
Fri, 24th Jun 2011 4:39 pm
-
Sathya on
Wed, 29th Jun 2011 5:40 am
-
Steven Robert on
Wed, 29th Jun 2011 10:47 pm
-
thinker8 on
Sun, 10th Jul 2011 10:53 pm
-
Vijay on
Mon, 11th Jul 2011 4:41 am
-
Sandy on
Thu, 1st Sep 2011 3:18 am
-
Pietro on
Thu, 20th Oct 2011 10:20 am
-
soul_killer on
Tue, 1st Nov 2011 4:26 am
-
soul_killer on
Tue, 1st Nov 2011 4:51 am
-
google plus on
Wed, 9th Nov 2011 1:21 am
-
Java Coaching In Indore on
Wed, 30th Nov 2011 6:10 am
-
Vinu on
Tue, 24th Jan 2012 6:20 pm
-
Sita on
Mon, 4th Jun 2012 5:43 am
-
Sita on
Mon, 4th Jun 2012 6:25 am
-
Vara Prasad Bokka on
Wed, 13th Jun 2012 9:00 am
-
Sita on
Tue, 19th Jun 2012 2:25 pm
-
Vinay Badgoti on
Fri, 22nd Jun 2012 8:19 am
-
Vicky on
Wed, 4th Jul 2012 9:49 am
-
Ella on
Wed, 4th Jul 2012 10:04 am
-
Steven Wall on
Wed, 4th Jul 2012 1:57 pm
-
vaibhav on
Tue, 18th Sep 2012 8:47 am
-
jai on
Tue, 16th Oct 2012 7:00 am
-
gdhanu11 on
Thu, 1st Nov 2012 2:11 am
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,
What about pictures in this post, i have problem to see them !
Thanks for pointing that I fixed that now pls check.
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?
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.
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
I want to show a feed form, instead of taking one time permission, what should I do?
Hello Edward I have added one more simple way to do this. Just execute the above URL in step3 to generate Session key.
Yes Amaikanith, Check this link on how to show a feedform http://forum.developers.facebook.com/viewtopic.php?pid=139729
Thank you very much.
Edward
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!
Hi Dikla, You can just use that last program to publish.
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; } }
my netbeans IDE just underlines the client.setisdesktop(true) PART ….
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.
Hassana, did u given permission to your application?
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
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
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?
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
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.
Boris, You can just change the next URL to your url that you given in Facebook connet URL.
for example: In below url I used blog.theunical.com
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
Thanks Manu, pointing that out, Here is the link to download http://blog.theunical.com/wp-content/uploads/2010/05/facebook-platform.tar1.gz
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?
Thanks,
This works. yeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
Thanks again
Devinka: Can you get it working?
getting below error, when trying to execute the above code…..
com.google.code.facebookapi.FacebookException: Incorrect signature
hi…..steven..
it works…..thanks……alot
but the….. can’t we write some others wall…….if so what should be done
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…
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).
——————————————————————————————————-
hi guys…. thanks i got the answer already…
and thank so much ur page very helpul….
Thanks & Regards,
Meelo =p
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.
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.
@Prasi yes just replace that APIkey , secret and session key in php code that i zipped (in my other post http://blog.theunical.com/facebook-integration/5-steps-to-publish-on-a-facebook-wall-using-php/ )and its done. if u have those keys ready
@Jita jdk1.5 would be better, if that lib is not available with u then download it.
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.
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.
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.
@jita are u getting any error? if yes then chk all the 5 steps again
@Prasi, u can generate from the given url if the settings are not done correctly then u will get an error like this, so pls chk the steps exactly.
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
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”) ?
@Catalin, you can’t give local URL, only public URL will work
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.
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
@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
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.
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.
@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.
@ Kiran..
Me tooo need the same… can any one help us ??
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.
@Rohit try this method http://blog.theunical.com/facebook-integration/add-picture-on-facebook-wall-using-php/
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.
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
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
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.
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
@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.
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);
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)
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
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
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.
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..
Plus +1′s Available including affordable seo packages
I really appreciate your post and you explain each and every point very
well.Thanks for sharing this information.And I’ll love to read your
next post too.
Regards
Thank you for the tips & code snippet. It works well !
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..
Hi, i am searching the solution that how to give authorization to my facebook app to post on other’s wall.
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.
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.
Thankzz Man.. This URL served My purpose.. Now im comfortably building my app in java.. !!!!
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.
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.
@Ella
you shud not run the session program again
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..
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
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…..
Tell me what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!





