title: twitter4j 401 authentication error persisting AccessToken
body: <p>I am having a hard time trying to figure out what's going on. I have the typical app structure that spawns one OAuthActivity that takes care of getting a twitter token, then my main application activity uses that token for various twitter-related operations.</p>
  
  <p>My OAuthActivity works. I get an auth token, and the Twitter web screen correctly shows my application name, etc.... Besides, <strong>inside that activity</strong>, I can send a tweet and <strong>it gets published.</strong> . This means the OAuthActivity works, the <strong>clock is in sync</strong>, the <strong>token is valid</strong>, etc...</p>
  
  <p>But when this OAuthActivity finishes and returns to the calling activity, whenever I try to use that token (<strong>recreating it from the persisted key/secret</strong>), no matter for what, the operation <strong>always</strong> fails with a 401, complaining that AuthChallenge reported null... just like if I provided an empty token, <strong>but i haven't</strong> !!!</p>
  
  <p>Please find attached the source of my OAuthActivity, and the source of how I initialize Twitter Objects in the main activity. Please tell me if you see something wrong. </p>
  
  <p>PD - <strong>I have obviously checked that the token values I assign are the same I get</strong> !! Also tried different ways of instantiating Twitter, via properties, via builder, via sets .... and nothing changes :(</p>
  
  <p>EDIT-> I found around I have to call "<strong>verifyCredentials()</strong>" on the new twitter object if I want to reuse a token, but .... no luck! (please find posted exception at the end)</p>
  
  <p>EDIT-2> If I use on both the child activity and the parent </p>
  
  <pre><code>mTwitter=TwitterFactory.getSingleton()
  </code></pre>
  
  <p>then the twitter object works, but this is not really acceptable for me because It doesnt use persistance, and I would need to authorize the application everytime. Besides, only Twitter object is authorized, TwitterStream keeps throwing exceptions.</p>
  
  <p>Cheers!</p>
  
  <p>Source code of the parent activity, where I try to use an access token obtained in the child activity, listed below. Whatever I try to do with this token always gets the 401.</p>
  
  <pre><code>private void init_twitter(String tok, String sec) {
  
      ConfigurationBuilder cb = new ConfigurationBuilder();
  
      cb.setDebugEnabled(true)
        .setOAuthConsumerKey(Conf.OAUTH_CONSUMER_KEY)
        .setOAuthConsumerSecret(Conf.OAUTH_CONSUMER_SECRET)
        .setOAuthAccessToken(tok)
        .setOAuthAccessTokenSecret(sec);
  
      TwitterFactory tf = new TwitterFactory(cb.build());
  
      mTwitter=tf.getInstance();
  
  
  
      /** This always fails, even though I call this routine with the 
                  correct token &amp; secret !!! See at the enf of message for an alternate 
                  routine like this one that makes use of verifyCredentials and
                  also fails. */ 
  
      new Thread(new Runnable() {
  
          @Override
          public void run() {
              // TODO Auto-generated method stub
              try {
                  mTwitter.updateStatus("yello 2");
              } catch (TwitterException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
  
          }}).start();
  
  
  }
  </code></pre>
  
  <p>SOurce Code of the child OAuthActivity, it apparently works as I get an access token &amp; am able to tweet:</p>
  
  <pre><code>import a lot;
  
  public class TwitterLogin extends Activity {
  
      private final String TAG = "TwitterLogin";
      public final static String PREF_KEY_OAUTH_TOKEN="twitter.oauth.token", PREF_KEY_OAUTH_SECRET="twitter.oauth.secret", PREF_KEY_TWITTER_LOGIN="twitter.oauth.login";
  
      private SharedPreferences mPreferences;
  
      private Twitter twitter = new TwitterFactory().getInstance();
  
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          Log.i(TAG, "Starting task to retrieve request token.");
          this.mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
          super.onCreate(savedInstanceState);
          getActionBar().setTitle("TWITTER AUTHENTICATION");
  
  
      }
  
      private void returnParent(boolean result)  {
          setResult(result?Activity.RESULT_OK:Activity.RESULT_CANCELED, null);
          if (Conf.LOG_ON) Log.d(TAG, "TWITTER AUTH: END PROCESS , GLOBAL RESULT "+result);
  
          /** THE FOLLOWING THING WORKS !!!!! IT SUCCESSFULLY TWEETS */
  
          new Thread(new Runnable() {
  
              @Override
              public void run() {
                  // TODO Auto-generated method stub
                  try {
                      twitter.updateStatus("yello");
                  } catch (TwitterException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
  
              }}).start();
  
  
  
          finish();
      }
  
      /**
       * Uses TWITTER4J to get the Request URL. It gets something like 
       * AUTH URL TWITTER4J IS http://api.twitter.com/oauth/authorize?oauth_token=xxxxxxxxxxxxxxxxxxxxx
       *
       * @return The Request URL to open in webview and get the Verifier
       */
  
      private String oauth_twitter4j_getRequestUrl() throws TwitterException {
          twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
          RequestToken tempToken = twitter.getOAuthRequestToken(Constants.OAUTH_CALLBACK_URL);
          return tempToken.getAuthorizationURL();
      }
  
  
      @Override
      protected void onResume() {
          super.onResume();
          WebView webview = new WebView(this);
          webview.getSettings().setJavaScriptEnabled(true);  
          webview.setVisibility(View.VISIBLE);
          setContentView(webview);
  
          Log.i(TAG, "Retrieving request token from Google servers");
  
          try {
  
              StrictMode.ThreadPolicy policy = new StrictMode. ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);
  
              String authorizationUrl=oauth_twitter4j_getRequestUrl();
              Log.d(TAG, "AUTH URL TWITTER4J IS "+authorizationUrl_t);
  
              webview.setWebViewClient(new WebViewClient() {  
  
                  @Override
                  public boolean shouldOverrideUrlLoading(WebView webView, String url) { 
                      if (Conf.LOG_ON) Log.d(TAG,"WebView: "+url);
                      if (url != null &amp;&amp; url.startsWith(Constants.OAUTH_CALLBACK_URL)) try {
                          System.out.println("TWEET TWEET TWEET");
                          retrieveAccessToken(url); //added this
                          webView.setVisibility(View.GONE); //added this
                          return true;            
                      } catch (Exception e) {
                          e.printStackTrace();
                          returnParent(false);
                          return true;
                      } else return false;
                  }
  
                  private void saveAccessToken(AccessToken accessToken) {
  
                      // Shared Preferences
                      Editor e = mPreferences.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());
                      e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                      e.commit(); 
  
                      Log.e("Twitter OAuth Token", "&gt; " + accessToken.getToken()+"-"+accessToken.getScreenName());
  
                  }
  
                  private void retrieveAccessToken(String url) throws Exception {
                      String requestToken  = extractParamFromUrl(url,"oauth_token");
                      String verifier= extractParamFromUrl(url,"oauth_verifier");
                      if (Conf.LOG_ON) Log.d(TAG, "Tenemos ACCESS TOKEN y VERIFIER :"+requestToken+","+verifier+","+(new Date().toString()));
  
                      if (ONLY_TWITTER4J)
                          retrieveAccessToken_with4j(verifier);
                      else
                          retrieveAccessToken_signpost(verifier);
                  }
  
                  private void retrieveAccessToken_with4j(String verifier) throws TwitterException {
                      AccessToken a=twitter.getOAuthAccessToken(verifier);
                      saveAccessToken(a);
                      returnParent(true);
                  }
  
                  private String extractParamFromUrl(String url,String paramName) {
                      String queryString = url.substring(url.indexOf("?", 0)+1,url.length());
                      QueryStringParser queryStringParser = new QueryStringParser(queryString);
                      return queryStringParser.getQueryParamValue(paramName);
                  }  
  
              });  
  
              webview.loadUrl(authorizationUrl);  
          } catch (Exception ex) {
              ex.printStackTrace();
          }
      }
  
  }
  </code></pre>
  
  <p>Exception I get when calling VerifyCredentials with the token I'm sure is right:</p>
  
  <pre><code>    Received authentication challenge is null
      W/System.err(24915): Relevant discussions can be found on the Internet at:
      W/System.err(24915):    http://www.google.co.jp/search?q=6f0f59ca or
      W/System.err(24915):    http://www.google.co.jp/search?q=20d0f74e
      W/System.err(24915): TwitterException{exceptionCode=[6f0f59ca-20d0f74e 1de2170b-f94dee38], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
      W/System.err(24915):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:192)
      W/System.err(24915):    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
      W/System.err(24915):    at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:89)
      W/System.err(24915):    at twitter4j.TwitterBaseImpl.fillInIDAndScreenName(TwitterBaseImpl.java:126)
      W/System.err(24915):    at twitter4j.TwitterImpl.verifyCredentials(TwitterImpl.java:592)
      W/System.err(24915):    at com.regaliz.helpers.TwitterManager$2.run(TwitterManager.java:140)
      W/System.err(24915):    at java.lang.Thread.run(Thread.java:856)
      W/System.err(24915): Caused by: java.io.IOException: Received authentication challenge is null
      W/System.err(24915):    at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:397)
      W/System.err(24915):    at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:345)
      W/System.err(24915):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:276)
      W/System.err(24915):    at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479)
      W/System.err(24915):    at twitter4j.internal.http.HttpResponseImpl.&lt;init&gt;(HttpResponseImpl.java:34)
      W/System.err(24915):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:156)
      W/System.err(24915):    ... 6 more
  </code></pre>
  
  <p>This is the function modified to make use of verifyCredentials:</p>
  
  <pre><code>    private void init_twitter_2(final String tok, final String sec) throws TwitterException {
  
              ConfigurationBuilder cb = new ConfigurationBuilder();
  
              cb.setDebugEnabled(true)
                .setOAuthConsumerKey(Conf.OAUTH_CONSUMER_KEY)
                .setOAuthConsumerSecret(Conf.OAUTH_CONSUMER_SECRET);
      //        .setOAuthAccessToken(tok)
      //        .setOAuthAccessTokenSecret(sec);
  
              TwitterFactory tf = new TwitterFactory(cb.build());
  
              mTwitter=tf.getInstance();
              Log.d(TAG, "init_twitter_2 "+tok+","+sec);
              new Thread(new Runnable(){
  
                  @Override
                  public void run() {
                      // TODO Auto-generated method stub
                      User u;
                      try {
                          /** also tried setting token&amp;secret like this, instead of in the builder--&gt;no success */
                          mTwitter.setOAuthAccessToken(new AccessToken(tok,sec));
                          u = mTwitter.verifyCredentials();
                          Log.d(TAG, "User: "+u.getName());
  
                      } catch (TwitterException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                  }}).start();
  
  
          }
  </code></pre>