Wednesday, 4 January 2017

JAVA integration with twitter






JAVA integration with twitter


Go to the URL https://apps.twitter.com/ and create a new application. Give access level in ‘Settings’ as ‘Read, Write and Access direct messages’. You will get both consumer key and secret.

And  go to settings and check the permissions to read write and direct messages

Get

Consumer Key

Consumer Secret

see the screen


And also generate by clicking on generate access token it will display

Access Token
Access Token Secret.


Add dependency

<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>4.0.2</version>
</dependency>

Or 
 
Else we can add jar twitter4j-core


Code:


import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class JavaTweet {

static String consumerKeyStr = "PASTE CONSUMER KEY HERE";
static String consumerSecretStr = "PASTE CONSUMER SECRET HERE";
static String accessTokenStr = "PASTE ACCESS TOKEN HERE";
static String accessTokenSecretStr = "PASTE ACCESS TOKEN SECRET HERE";

public static void main(String[] args) {

try {
Twitter twitter = new TwitterFactory().getInstance();

twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);
AccessToken accessToken = new AccessToken(accessTokenStr,
accessTokenSecretStr);

twitter.setOAuthAccessToken(accessToken);

twitter.updateStatus("TWEET ON TWITTER EXAMPLE");

System.out.println("Successfully updated the status in Twitter.");
} catch (TwitterException te) {
te.printStackTrace();
}
}

}



That’s great. We have done it.
______________________________________________________________________________

We have also a neither way to tweet using java by Twitter REST API. For that we need

commons-codec-1.6.jar
  • commons-io-2.4.jar
  • commons-logging-1.1.3.jar
  • httpclient-4.3.1.jar
  • httpcore-4.3.jar
  • signpost-core-1.2.1.2.jar
  • signpost-commonshttp4-1.2.1.2.jar
All these jar files.


And code is as follows.


import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class JavaRestTweet {
static String consumerKeyStr = "PASTE CONSUMER KEY HERE";
static String consumerSecretStr = "PASTE CONSUMER SECRET HERE";
static String accessTokenStr = "PASTE ACCESS TOKEN HERE";
static String accessTokenSecretStr = "PASTE ACCESS TOKEN SECRET HERE";


public static void main(String[] args) throws Exception {
OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKeyStr,
consumerSecretStr);
oAuthConsumer.setTokenWithSecret(accessTokenStr, accessTokenSecretStr);

HttpPost httpPost = new HttpPost(
"http://api.twitter.com/1.1/statuses/update.json?status=Hello%20Twitter%20Exammple.");

oAuthConsumer.sign(httpPost);

HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);

int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println(statusCode + ':'
+ httpResponse.getStatusLine().getReasonPhrase());
System.out.println(IOUtils.toString(httpResponse.getEntity().getContent()));

}
}


That’s great. We have done it.

Small JS to LOGIN to FB and POST on ur wall



<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Posting Job Opening To FB Wall</title>
<script type="text/javascript" src=""></script>
    </head>
    <body class="">
    <div id="fb-root" class=" fb_reset">
    <script>
var APP_ID="APP ID HERE";

window.fbAsyncInit = initFacebook;

function initFacebook()
{
    FB.init({
      appId  : APP_ID,
      status : true, // check login status
      cookie : false, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });

    FB.getLoginStatus(onFacebookLoginStatus);
};

(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
    }());
    //the login function
function facebookLogin()
{
    var loginUrl="http://www.facebook.com/dialog/oauth/?"+
        "scope=publish_actions&"+
        "client_id="+APP_ID+"&"+
        "redirect_uri="+document.location.href+"&"+
        "response_type=token";
    window.location=loginUrl;
}


//Callback function for FB.login
function onFacebookLoginStatus(response)
{
    if (response.status=="connected" && response.authResponse)
    {
        document.getElementById("txtEcho").innerHTML="Logged in.";

    }
    else
    {
        document.getElementById("txtEcho").innerHTML="Not logged in.";
    }

}


    //post to wall function
function postToWallUsingFBApi()
{
  
 FB.ui({
method: 'feed',
link: 'http://Examplesite.net/join-us/',
description:'Example description',
caption: 'Example Caption',
}, function(response){});

}

    //the return function after posting to wall
function onPostToWallCompleted(response)
{
    if (response)
    {
        if (response.error)
        {
            document.getElementById("txtEcho").innerHTML=response.error.message;
        }
        else
        {
            if (response.id)
                document.getElementById("txtEcho").innerHTML="Posted as post_id "+response.id;
            else if (response.post_id)
                document.getElementById("txtEcho").innerHTML="Posted as post_id "+response.post_id;
            else
                document.getElementById("txtEcho").innerHTML="Unknown Error";
        }
    }
}



    </script>
    <input id="loginButton" type="button" value="Login To Facebook" onclick="javascript:facebookLogin();">
    <input id="postToWallWithFBApiPrompt" type="button" value="Post To Wall Using FB.api"          onclick="javascript:postToWallUsingFBApi();">
    <div id="txtEcho"><b></b></div>
    </body>
    </html>

Intigration with Facebook Using java








Intigration with Facebook Using java


First we need register our app in

And in settings put domains as
https://sssss.com

And there we can get the appid and Secret Key

APPID
XXXXXXXXXXXXXX

Secret key
XXXXXXXXXXXXXXXX


And after settings all these go to


And login with the credentials

After that click on the down arrow on get token, after that click on the checkbox publish_actions and click on get token after that token will generate. Copy that token and paste the token in the program.

Run the program.

Post will be posted on the user who has been logged in.


Maven dependency

<dependency>
<groupId>org.scribe</groupId>
<artifactId>scribe</artifactId>
<version>1.3.2</version>
</dependency>


JAVA Code

package com.restfb.example;


import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.FacebookApi;
import org.scribe.model.*;
import org.scribe.oauth.OAuthService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class SharePostOnFacebookWallTimeline {

private static String FB_APP_KEY = "APPID HERE";
private static String FB_APP_SECRET = "APP SECRET HERE";

private static OAuthService getOAuthService()
{
return new ServiceBuilder()
.provider(FacebookApi.class)
.apiKey(FB_APP_KEY)
.apiSecret(FB_APP_SECRET)
.callback("https://yoursite.net/")
.build();
}



private static void postOnFacebookWallTimeline (OAuthService oAuthService, Token accessToken)
{
OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/me/feed");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
String message = "Welocme to Techwave here we are Having 5 oepenings on JAVA - " + sdf.format(new Date());
request.addBodyParameter("message", message);
String link = "https://yoursite.net";
request.addBodyParameter("link", link);
oAuthService.signRequest(accessToken, request);

Response response = request.send();
System.out.println(response.getCode());
String responseBody = response.getBody();
System.out.println(responseBody);
}

public static void main(String[] args)
{
OAuthService oAuthService = getOAuthService();

Token accessToken, accessToken1;

//facebook app's short-lived access token
//accessToken = getFbAppShortLivedAccessToken(oAuthService);
//accessToken = new Token("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "");

//facebook app's long-lived access token
//accessToken1 = getFbAppLongLivedAccessToken(oAuthService, accessToken);
accessToken = new Token("Paste accesstoken here", "");

//postOnFacebookWallTimeline(oAuthService, accessToken1);
postOnFacebookWallTimeline(oAuthService, accessToken);

}

}