How to use the twitter4j lib to get the tweets of screen name?

后端 未结 1 886
别跟我提以往
别跟我提以往 2021-01-24 01:52

I have seen a lot of tutorials for using this lib but i dint get a clear idea of it.

Firstly how can i authenticate the twitter app??,

is there any way i can har

1条回答
  •  天涯浪人
    2021-01-24 02:22

    There are multiple ways to authenticate:

    • The standard 3-legged authorization : I'll be explaining this briefly in this answer.

    • Pin-based authorization : For applications which cannot access or embed a web browser.

    • xAuth : Functions as an Application Authorization, so the user does not need to log in but uses the application to authorize.

    First of all you will need to create an application here. You will then receive your consumer key and secret:

    Consumer key

    You can then use this code to request authorization at start up.

    public class MainActivity extends Activity {
    
        // TwitterProperties
        private CommonsHttpOAuthConsumer httpOauthConsumer;
        private OAuthProvider httpOauthprovider;
    
        public final static String consumerKey = "YOUR CONSUMER KEY";
        public final static String consumerSecret = "YOUR CONSUMER SECRET";
    
        private final String CALLBACKURL = "SCHEME://HOST";
    
        private Twitter twitter;
        AccessToken a;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            StrictMode.enableDefaults();
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.activity_main);
    
            doAuth();
        }
    
        private void doAuth() {
            try {
                httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,
                        consumerSecret);
                httpOauthprovider = new DefaultOAuthProvider(
                        "https://twitter.com/oauth/request_token",
                        "https://twitter.com/oauth/access_token",
                        "https://twitter.com/oauth/authorize");
                String authUrl = httpOauthprovider.retrieveRequestToken(
                        httpOauthConsumer, CALLBACKURL);
    
                this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                        .parse(authUrl)));
            } catch (Exception e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    
    
        @Override
        protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
    
            Uri uri = intent.getData();
            if (uri != null && uri.toString().startsWith(CALLBACKURL)) {
    
                String verifier = uri
                        .getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
    
                // this will populate token and token_secret in consumer
                try {
                    httpOauthprovider.retrieveAccessToken(httpOauthConsumer,
                            verifier);
                } catch (OAuthMessageSignerException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (OAuthNotAuthorizedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (OAuthExpectationFailedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (OAuthCommunicationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
    
                //Important part where it actually sets the authorization so you can use it
                a = new AccessToken(httpOauthConsumer.getToken(),
                        httpOauthConsumer.getTokenSecret());
                twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(consumerKey, consumerSecret);
                twitter.setOAuthAccessToken(a);
            }
        }
    
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    }
    

    To make this work you need to make a couple adjustments to your Manifest.

    • Give it permission to use internet:
        
    
    • Set the launch mode to singleInstance
        
    
    • Add this intent-filter
    
        
        
    
        
        
    
        
        
    
        
        
    
    

    Make sure to have the same host and scheme in your Activity:

    private final String CALLBACKURL = "SCHEME://HOST";
    

    Now that you have successfully authorized your app you can use the Twitter object to request timelines etc.

    Example:

    private void getTweets(String user) {
    
        try {
            List statuses;
            statuses = twitter.getUserTimeline(user);
    
            System.out.println("Showing @" + user + "'s user timeline.");
            for (Status status : statuses) {
    
                System.out.println("@" + status.getUser().getScreenName()
                        + " - " + status.getText());
            }
    
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
        }
    
    }
    

    Voilá!

    0 讨论(0)
提交回复
热议问题