This is continuation of article Login With Twitter Using Java. By using Twitter OAuth features, If you want to update status of user from your java web application, This article will help you. Suppose if you create a news sharing website, Your website will get more traffic if users share those news on their twitter's timeline. They can do that directly from your application if they given access to your application. Twitter is having java library twitter4j to access twitter services. Download twitter4j and add those jars to WEB-INF folder.
--- Click here to see demo --- Download eclipse code ---
There are 2 types of Update Status features are there.
I have provided sample project here, download it. Open Setup.java and give your twitter app credentials, database credentials. Create MySQL database schema with name "demos". Created below specified table. Import this project into Eclipse, add it to tomcat server, run index.html
- Update status to your own profile using access token and access token secret which were generated manually
- Update status on user's timeline using oauth access token and access token secret that were saved in database
Process - Oauth Status Update
- Register your application in twitter developers page
- Provide access link to user ( Generate link using Twitter4j )
- User will be redirected to twitter access page. User will give permission to application
- Access token will be sent to Callback URL
- Get access token and store it in database
- Whenever you want to update status on user's timeline, get access token from access token secret from database and update status using them
// configure twitter object with consumer key and consumer secret ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey(Setup.CONSUMER_KEY) .setOAuthConsumerSecret(Setup.CONSUMER_SECRET); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); // get user details from by user id UserPojo user = TwitterDAO.selectUser(4); // set access token and access token secret and user id AccessToken accessToken1 = new AccessToken(user.getAccess_token(), user.getAccess_token_secret(), user.getTwitter_User_id()); twitter.setOAuthAccessToken(accessToken1); // update status from twitter.updateStatus("Sample tweet from standalone java");
Process - Status Update To Your Own Profile
If you want to update status to your own profile, you can do it with default access token and access token secret. Observe below screenshot.
Build AccessToken object with above access token and access token secret and user id. Update status as like above