9

I am using twitter4j to send tweet from my application. When I invoke the method retrieveRequestToken, I get the error "Communication with the service provider failed: null".

public static void askOAuth(Context context) {
    try {
        // Use Apache HttpClient for HTTP messaging
        consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        provider = new CommonsHttpOAuthProvider(
                "https://api.twitter.com/oauth/request_token",
                "https://api.twitter.com/oauth/access_token",
                "https://api.twitter.com/oauth/authorize");
        String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
        Toast.makeText(context, "Authorize this app!", Toast.LENGTH_LONG).show();
        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
    } catch (Exception e) {
        Log.e(APP, e.getMessage());
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

Thank you.

Guillermo Tobar
  • 344
  • 4
  • 17

6 Answers6

12

If this is in ICS, I highly recommend against using StrictMode.enableDefaults;.

ICS does not allow Http requests to occur in the UI thread, so when you do as above, you get that error.

To fix this, do provider.retrieveRequestToken(consumer, CALLBACK_URL); in a background thread as well as provider.retrieveAccessToken(consumer, verifier);.

Source: http://code.google.com/p/oauth-signpost/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary&groupby=&sort=&id=71

Grantland Chew
  • 2,620
  • 26
  • 26
  • Fantastic! Great answer. Would have never figured it out myself. Spent two days on this issue. Thanks. Grantland Chew, you are THE MAN! – Abhijit Feb 16 '12 at 21:26
  • I'm already making these calls in separate thread but still I'm facing this issue ONLY after using Proguard. And I have excluded Twitter4j already from proguard-project.txt. Any idea? – Nayanesh Gupte Dec 04 '14 at 05:21
2

I finally found the problem, he has to do with StrictModes in the latest versions of android. Running StrictMode.enableDefaults(); before making the call, the problem is corrected.

Although it worked for me, I would like to know if there is a more elegant solution to correct the problem.

Yuck
  • 49,664
  • 13
  • 105
  • 135
Guillermo Tobar
  • 344
  • 4
  • 17
1

Have added permission tag regarding using "INTERNET" in android manifest file.

TAG ------>

Happy Coding... :-)

Rocker
  • 669
  • 5
  • 15
0

try inside OnCreate():

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
Duna
  • 1,564
  • 1
  • 16
  • 36
0

Example of the AsyncTask

    /**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class RequestTask extends AsyncTask<Void, Void, Boolean> {
    String content;
    private ProgressDialog dialog;

    protected void onPreExecute() {
        dialog = new ProgressDialog(LoginUsingTwitterActivity.this);
        dialog.setMessage("Loading...");
        dialog.setCancelable(false);
        dialog.show();
    }

    protected Boolean doInBackground(Void... params) {
        httpOauthConsumer = new CommonsHttpOAuthConsumer(
                TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
        httpOauthprovider = new DefaultOAuthProvider(REQUEST_URL,
                ACCESS_URL, AUTHORIZE_URL);
        try {
            authUrl = httpOauthprovider.retrieveRequestToken(
                    httpOauthConsumer, CALLBACK_URL);
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
            return false;
        } catch (OAuthNotAuthorizedException e) {
            e.printStackTrace();
            return false;
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
            return false;
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (success == true) {
            Log.e("LoginUsingTwitterActivity", "onPostExecute");
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        }
        dialog.dismiss();
    }

    @Override
    protected void onCancelled() {
        dialog.dismiss();
        mAuthTask = null;
    }
}
Adrian
  • 336
  • 6
  • 22
0

Check Two Steps

1-Give Callback URL in Your twitter app created by you on twitter website
2-Go to Phone settings then click 'Date and Time' and select 'Automatic'

Atul Bhardwaj
  • 6,647
  • 5
  • 45
  • 63
  • @GuillermoTobar Please check this link http://stackoverflow.com/questions/6324474/problem-with-oauth-twitter-and-android-fails-in-http-communication-with-the-se/9987465#9987465 – Atul Bhardwaj Sep 27 '12 at 05:17