Search code examples
javaeclipsetwitteroauth-2.0twitter-oauth

Can we post to twitter only for user for which twitter app is created?


In my app, should I access tokens to each user? Because I am able to post messages and images to Twitter using Java. But, it posts only to application created account. If I want to post to other Twitter accounts, what should I do?

Here is the code:

package com.javapapers.java;

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

public class JavaTweet {

static String consumerKeyStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String consumerSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String accessTokenStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String accessTokenSecretStr = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";

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("Post using Twitter4J Again");

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

What should I do so that messages get posted to the user who is logged in with a different user?


Solution

  • If you're making a website, you redirect the user to Twitter, they authorize your app, then Twitter redirects back to your website with a Authorization Token, then you call a REST API with that token to get an Access Token. This is called the Authorization Code Grant flow (OAuth2 spec) or 3-legged authentication (Twitter).

    For other use cases, see See Obtaining access tokens (Twitter).