TwitterException with twitter4j when opening login page on Android


#1

Until now, I can use login page without any problem. Now, I am getting the following error. I am using twitter4j to login. I am sure that I can’t reach API limits while developing. To be sure, I have changed keys, but getting the same error.

Any help is appreciated.

01-14 21:47:06.333: W/System.err(24243): 403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (https://support.twitter.com/articles/15364-about-twitter-limits-update-api-dm-and-following).
01-14 21:47:06.333: W/System.err(24243): Relevant discussions can be found on the Internet at:
01-14 21:47:06.333: W/System.err(24243): http://www.google.co.jp/search?q=10f5ada3 or
01-14 21:47:06.333: W/System.err(24243): http://www.google.co.jp/search?q=dceba039
01-14 21:47:06.333: W/System.err(24243): TwitterException{exceptionCode=[10f5ada3-dceba039], statusCode=403, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.6}
01-14 21:47:06.333: W/System.err(24243): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:185)
01-14 21:47:06.333: W/System.err(24243): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
01-14 21:47:06.333: W/System.err(24243): at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
01-14 21:47:06.333: W/System.err(24243): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
01-14 21:47:06.333: W/System.err(24243): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
01-14 21:47:06.333: W/System.err(24243): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
01-14 21:47:06.333: W/System.err(24243): at …LoginActivity$TwitterLogin.doInBackground(LoginActivity.java:134)
01-14 21:47:06.333: W/System.err(24243): at …android.LoginActivity$TwitterLogin.doInBackground(LoginActivity.java:1)
01-14 21:47:06.343: W/System.err(24243): at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-14 21:47:06.343: W/System.err(24243): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-14 21:47:06.343: W/System.err(24243): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-14 21:47:06.343: W/System.err(24243): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-14 21:47:06.343: W/System.err(24243): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-14 21:47:06.353: W/System.err(24243): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-14 21:47:06.353: W/System.err(24243): at java.lang.Thread.run(Thread.java:864)


#2

Upgrading twitter4j to the latest version is fixed my problem. Sorry for useless thread.


#3

hi Selahaddin Akgün, i have same problem in android. Could you tell me the solotion to solved this?


#4

Hi HnRinlv,
I am using twitter4j. Its version was 2.6.x. I upgraded it to the latest version 3.0.5. That solved my problem.


#5

Hi Selahaddin Akgün , I got that error too and I’m using lastest version 3.0.5 but still get that error … do you have any other solution …


#6

my problem is solved by change 1 state in configuration from

builder.setUseSSL(fase);
to
builder.setUseSSL(true);

in login configuration


#7

thank’s Mr.@slhddn_ Selahaddin Akgün, i solved my same problem with your suggestion.


#8

Thanks @lu_gen Nguyễn Lê Hùng, this helped me! :slight_smile:


#9

good to hear that your problem is solved :slight_smile:


#10

Which android version you use?


#11

I have also the same problem.
I am using latest twitter4j-core-3.0.5.jar library.

I am getting error:

oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.

even everything was ok before the twitter has upgraded to SSL/TSL.

so how do I resolve this issue.

If you have some code, then please provide for it;s solution.

Thanking in Advance.


#12

Have you tried @lu_gen 's solution?


#13

@whofme yes, I have used. I have problem in start of Authorizing.
For login, there is not configuration required.

authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);

this throws the exception.

Please provide, some running sample for authentication.


#14

@whofme yes, I have used. I have problem in start of Authorizing.

authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);

this throws the exception.

I am doing this way:
TwitterApp.context = context;
mTwitter = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(AppConsts.TWITTER_CONSUMER_KEY, AppConsts.TWITTER_CONSUMER_SECRET);
mHttpOauthprovider = new DefaultOAuthProvider(TWITTER_REQUEST_URL, TWITTER_ACCESS_TOKEN_URL, TWITTER_AUTHORZE_URL);
mAccessToken = mSession.getAccessToken();

if (mAccessToken != null)
{
mTwitter.setOAuthConsumer(AppConsts.TWITTER_CONSUMER_KEY, AppConsts.TWITTER_CONSUMER_SECRET);
mTwitter.setOAuthAccessToken(mAccessToken); }

else calling the authorize method:
public void authorize()
{
mProgressDlg.setMessage(“Loading …”);
mProgressDlg.show();

	new Thread()
	{
		@Override
		public void run()
		{
			String authUrl = "";
			int what = 1;

			try
			{
				authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);
				what = 0;
			}
			catch (Exception e)
			{
				new Utility().handleException(e);
			}
			mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
		}
	}.start();
}

#15

if you have some sample source running correctly then please send as I can overcome this issue.


#16

While twitter login, is read permission set in app permissions enough to authenticate user and fetch user profile data?


#17
package com.ptv.news;

import android.app.Activity;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.text.InputFilter.LengthFilter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Tweitter extends Activity {
Context context;
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = “YzJWF634UlXP”;
static String TWITTER_CONSUMER_SECRET =“FnD77qtqsyf7bCjIWN2Q0Q”;

// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "TWITTER_OAUTH_TOKEN";
static final String PREF_KEY_OAUTH_SECRET = "TWITTER_OAUTH_TOKEN_SECRET";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

static final String TWITTER_CALLBACK_URL = "oauth://com.hintdesk.Twitter_oAuth";

// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;

// Progress dialog
ProgressDialog pDialog;

// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
 
// Shared Preferences
private static SharedPreferences mSharedPreferences;
 
// Internet Connection detector
private ConnectionDetector cd;
 
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.twietr);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
     
    cd = new ConnectionDetector(getApplicationContext());
    
  /*  if (android.os.Build.VERSION.SDK_INT > 8) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
      }

*/
// Check if Internet present
if (!cd.isConnectingToInternet()) {

        // Internet Connection is not present
       alert.showAlertDialog(context, "Internet Connection Error",
               "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }
     
    // Check if twitter keys are set
    if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
        // Internet Connection is not present
        alert.showAlertDialog(context, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    // All UI elements
    btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
    btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
    btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
    txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
    lblUpdate = (TextView) findViewById(R.id.lblUpdate);
    lblUserName = (TextView) findViewById(R.id.lblUserName);

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences(
            "MyPref", 0);

    /**
     * Twitter login button click event will call loginToTwitter() function
     * */
    btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call login twitter function
        	
        			// TODO Auto-generated method stub
        			
        			 loginToTwitter();
        	
           
        }
    });

    /**
     * Button click event to Update Status, will call updateTwitterStatus()
     * function
     * */
    btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call update status function
            // Get the status from EditText
            String status = txtUpdate.getText().toString();

            // Check for blank text
            if (status.trim().length() > 0) {
                // update status
                new updateTwitterStatus().execute(status);
            } else {
                // EditText is empty
                Toast.makeText(getApplicationContext(),
                        "Please enter status message", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    /**
     * Button click event for logout from twitter
     * */
    btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call logout twitter function
            logoutFromTwitter();
        }
    });

    /** This if conditions is tested once is
     * redirected from twitter page. Parse the uri to get oAuth
     * Verifier
     * */
    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            String verifier = uri
                    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken accessToken = twitter.getOAuthAccessToken(
                        requestToken, verifier);

                // Shared Preferences
                Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET,
                        accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                // Hide login button
                btnLoginTwitter.setVisibility(View.GONE);

                // Show Update Twitter
                lblUpdate.setVisibility(View.VISIBLE);
                txtUpdate.setVisibility(View.VISIBLE);
                btnUpdateStatus.setVisibility(View.VISIBLE);
                btnLogoutTwitter.setVisibility(View.VISIBLE);
                 
                // Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);
                String username = user.getName();
                 
                // Displaying in xml ui
                lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }
    }

}

/**
 * Function to login twitter
 * */
private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
    	ConfigurationBuilder builder = new ConfigurationBuilder();
    	builder.setUseSSL(true);
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();
         
        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();

        try {
        	 requestToken = twitter
                     .getOAuthRequestToken(TWITTER_CALLBACK_URL);
             this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                     .parse(requestToken.getAuthenticationURL())));
        	// requestToken = twitter
              //       .getOAuthRequestToken(TWITTER_CALLBACK_URL);
        	 //Tweitter.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
               //      .parse(requestToken.getAuthenticationURL())));
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    } else {
        // user already logged into twitter
        Toast.makeText(getApplicationContext(),
                "Already Logged into twitter", Toast.LENGTH_LONG).show();
    }
}

/**
 * Function to update status
 * */
class updateTwitterStatus extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Tweitter.this);
        pDialog.setMessage("Updating to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Places JSON
     * */
    protected String doInBackground(String... args) {
        Log.d("Tweet Text", "> " + args[0]);
        String status = args[0];
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
             
            // Access Token
            String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
            // Access Token Secret
            String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
             
            AccessToken accessToken = new AccessToken(access_token, access_token_secret);
            Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
             
            // Update status
            twitter4j.Status response = twitter.updateStatus(status);
             
            Log.d("Status", "> " + response.getText());
        } catch (TwitterException e) {
            // Error in updating status
            Log.d("Twitter Update Error", e.getMessage());
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog and show
     * the data in UI Always use runOnUiThread(new Runnable()) to update UI
     * from background thread, otherwise you will get error
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Status tweeted successfully", Toast.LENGTH_SHORT)
                        .show();
                // Clearing EditText field
                txtUpdate.setText("");
            }
        });
    }

}

/**
 * Function to logout from twitter
 * It will just clear the application shared preferences
 * */
private void logoutFromTwitter() {
    // Clear the shared preferences
    Editor e = mSharedPreferences.edit();
    e.remove(PREF_KEY_OAUTH_TOKEN);
    e.remove(PREF_KEY_OAUTH_SECRET);
    e.remove(PREF_KEY_TWITTER_LOGIN);
    e.commit();

    // After this take the appropriate action
    // I am showing the hiding/showing buttons again
    // You might not needed this code
    btnLogoutTwitter.setVisibility(View.GONE);
    btnUpdateStatus.setVisibility(View.GONE);
    txtUpdate.setVisibility(View.GONE);
    lblUpdate.setVisibility(View.GONE);
    lblUserName.setText("");
    lblUserName.setVisibility(View.GONE);

    btnLoginTwitter.setVisibility(View.VISIBLE);
}

/**
 * Check user already logged in your application using twitter Login flag is
 * fetched from Shared Preferences
 * */
private boolean isTwitterLoggedInAlready() {
    // return twitter login status from Shared Preferences
    return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}

protected void onResume() {
    super.onResume();
}

}

i m facing the network main thread excption can any one plz help me thanks