Android: Login with Twitter using Twitter4J

我与影子孤独终老i 提交于 2019-11-27 19:12:05

It's because your app is registered as a desktop client. To overwrite callback URL, your app need to be registered as a browser client.

Try configuring a dummy callback URL (http://example.com/ or whatever you want) at https://dev.twitter.com/apps/[appid]/settings > Callback URL and your app will be recognized as a browser client.

Then try @Frankenstein or @jamn224 code.

First, you need to authenticate properly:

try{
        consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token", "http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
        String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);

        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));

    }catch(Exception e){
        Log.e(TAG,e+"");
    }

The necessities for CALLBACK_URL need to be set in the Manifest file (refer to Frankenstein's answer). The above code starts an intent to perform the authorization at Twitter's server. The callback information is necessary so the intent knows what app to return to after the authorization procedure.

Then we need to handle the return to the app after authenticating at Twitter:

    @Override
public void onResume(){
    super.onResume();

    if (this.getIntent()!=null && this.getIntent().getData()!=null){
        Uri uri = this.getIntent().getData();

        //handle returning from authenticating the user
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
            String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
            String token = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_TOKEN);
            try {  
                Twitter t = new TwitterFactory().getInstance();
                t.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

                // Get Access Token and store it  
                rToken = new RequestToken(token, CONSUMER_SECRET);
                AccessToken aToken = t.getOAuthAccessToken(rToken);
                storeAccessToken(aToken);  

                //send to checkLoginState again since we have authorization now!
                checkLoginState(); 

           } catch (Exception e) {  
               Log.e(TAG, e+"");  
           }  
          }  
         }
}//end onResume

This code grabs the data from the returning intent, among which is the info to grab the authorization token. "storeAccessToken(aToken)" is a short method i wrote that stores the token in the app's preferences so that we don't need to reauthorize every time the app is opened.

Now that we have an authorization token, we can use it authorize a Twitter instance:

twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(aToken);

The above variable "twitter" is now authorized and can do its thing.

you should be writing callback as this in manifest to your activity

<activity android:name="com.apps.twitter.PrepareRequestTokenActivity"
            android:launchMode="singleTask" android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:screenOrientation="portrait">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="x-oauthflow-twitter" android:host="callback" />
            </intent-filter>
</activity>

And in the Constant File

final public static String  CALLBACK_SCHEME = "x-oauthflow-twitter";    
final public static String  CALLBACK_URL = CALLBACK_SCHEME + "://callback";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!