1

我已经编写了将 Twitter 集成到 android 中的代码。我得到了第一个 scrren,当我向 twitt 写一些消息并单击 twitt 按钮时,我得到了以下异常,因为与服务提供商的 OauthCommunication 异常通信失败。我已经正确输入了消费者密钥消费者秘密。

Public class MainActivity extends Activity {
    private static final String TAG = "TwitterDemo";
    private static final String CONSUMER_KEY = "xxx";
    private static final String CONSUMER_SECRET = "xxx";
    private static final String CALLBACK_SCHEME = "twitter-OAUTH-test-app";
    private static final String CALLBACK_URL = CALLBACK_SCHEME + "://callback";
    private static final String TWITTER_USER = "androidtestacc1@gmail.com";

    private OAuthSignpostClient oauthClient;
    private OAuthConsumer mConsumer;
    private OAuthProvider mProvider;
    private Twitter twitter;
    SharedPreferences prefs;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

        mProvider = new DefaultOAuthProvider(
                "http://api.twitter.com/oauth/request_token",
                "http://api.twitter.com/oauth/access_token",
                "http://api.twitter.com/oauth/authorize");

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String token = prefs.getString("token", null);
        String tokenSecret = prefs.getString("tokenSecret", null);
        if (token != null && tokenSecret != null) {
            mConsumer.setTokenWithSecret(token, tokenSecret);
            oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
                    CONSUMER_SECRET, token, tokenSecret);
            twitter = new Twitter(TWITTER_USER, oauthClient);
        } else {
            Log.d(TAG, "onCreate. Not Authenticated Yet " );
            new OAuthAuthorizeTask().execute();
        }
    }

    class OAuthAuthorizeTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            String authUrl;
            String message = null;
            Log.d(TAG, "OAuthAuthorizeTask mConsumer: " + mConsumer);
            Log.d(TAG, "OAuthAuthorizeTask mProvider: " + mProvider);
            try {
                authUrl = mProvider.retrieveRequestToken(mConsumer,
                        CALLBACK_URL);
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(authUrl));
                startActivity(intent);
            } catch (OAuthMessageSignerException e) {
                message = "OAuthMessageSignerException";
                e.printStackTrace();
            } catch (OAuthNotAuthorizedException e) {
                message = "OAuthNotAuthorizedException";
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                message = "OAuthExpectationFailedException";
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                message = "OAuthCommunicationException";
                e.printStackTrace();
            }

            return message;
        }
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                Toast.makeText(MainActivity.this, result,
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    public void tweet(View view) {
        if (twitter == null) {
            Toast.makeText(this, "Authenticate first", Toast.LENGTH_LONG)
            .show();
            return;
        }
        EditText status = (EditText) findViewById(R.id.editTextTweet);
        new PostStatusTask().execute(status.getText().toString());
    }
    class PostStatusTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                twitter.setStatus(params[0]);
                return "Successfully posted: " + params[0];
            } catch (TwitterException e) {
                e.printStackTrace();
                return "Error connecting to server.";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Toast.makeText(MainActivity.this, result,
                    Toast.LENGTH_LONG).show();
        }

    }

    /* Responsible for retrieving access tokens from twitter */
    class RetrieveAccessTokenTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String message = null;
            String oauthVerifier = params[0];
            try {
                // Get the token
                Log.d(TAG, " RetrieveAccessTokenTask mConsumer: " + mConsumer);
                Log.d(TAG, " RetrieveAccessTokenTask mProvider: " + mProvider);
                Log.d(TAG, " RetrieveAccessTokenTask verifier: " + oauthVerifier);
                mProvider.retrieveAccessToken(mConsumer, oauthVerifier);
                String token = mConsumer.getToken();
                String tokenSecret = mConsumer.getTokenSecret();
                mConsumer.setTokenWithSecret(token, tokenSecret);

                Log.d(TAG, String.format(
                        "verifier: %s, token: %s, tokenSecret: %s", oauthVerifier,
                        token, tokenSecret));

                // Store token in prefs
                prefs.edit().putString("token", token)
                .putString("tokenSecret", tokenSecret).commit();

                // Make a Twitter object
                oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
                        CONSUMER_SECRET, token, tokenSecret);
                twitter = new Twitter(null, oauthClient);

                Log.d(TAG, "token: " + token);
            } catch (OAuthMessageSignerException e) {
                message = "OAuthMessageSignerException";
                e.printStackTrace();
            } catch (OAuthNotAuthorizedException e) {
                message = "OAuthNotAuthorizedException";
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                message = "OAuthExpectationFailedException";
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                message = "OAuthCommunicationException";
                e.printStackTrace();
            }
            return message;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                Toast.makeText(MainActivity.this, result,
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    /*
     * Callback once we are done with the authorization of this app with
     * Twitter.
     */
    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "intent: " + intent);

        // Check if this is a callback from OAuth
        Uri uri = intent.getData();
        if (uri != null && uri.getScheme().equals(CALLBACK_SCHEME)) {
            Log.d(TAG, "callback: " + uri.getPath());

            String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
            Log.d(TAG, "verifier: " + verifier);
            Log.d(TAG, " xxxxxxxxxxx mConsumer access token: " + mConsumer.getToken());
            Log.d(TAG, " xxxxxxxxxxxx mConsumer access token secret: " + mConsumer.getTokenSecret());
            Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN: " + OAuth.OAUTH_TOKEN);
            Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN_SECRET: " + OAuth.OAUTH_TOKEN_SECRET);

            new RetrieveAccessTokenTask().execute(verifier);
        }
    }

    public void logout(View view){

        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("token", null);
        editor.putString("tokenSecret", null);
        editor.commit();
        finish();
    }

}

错误

10-19 15:18:55.424: W/System.err(995): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://api.twitter.com/oauth/request_token
10-19 15:18:55.424: W/System.err(995):  at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
10-19 15:18:55.438: W/System.err(995):  at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
10-19 15:18:55.655: W/System.err(995):  ... 9 more
4

2 回答 2

1

尝试在您的应用中整合 twitter 的另一种方法

  1. 使用 auth & webview(Twitter4j 库)

http://davidcrowley.me/?p=410

http://www.mokasocial.com/2011/07/writing-an-android-twitter-client-with-image-upload-using-twitter4j/

代码(网址在网页视图中打开)

   twitter =  new TwitterFactory().getInstance();
   twitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
        TwitterConstants.CONSUMER_SECRET);
    RequestToken requestToken = null;
    try {
        requestToken = twitter.getOAuthRequestToken();
        System.out.println("requesttoken"+requestToken);
    } catch (TwitterException e) {
        e.printStackTrace();
    }

    twitterUrl = requestToken.getAuthorizationURL();



    ConfigurationBuilder builder = new ConfigurationBuilder();
  builder.setOAuthAccessToken(TwitterConstants.ACCESS_TOKEN);
  builder.setOAuthAccessTokenSecret(TwitterConstants.ACCESS_TOKEN_SECRET);
  builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
  builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
  OAuthAuthorization auth = new OAuthAuthorization(builder.build());
  twitter = new TwitterFactory().getInstance(auth);

   try {
    twitter.updateStatus("Hello World!");

    } catch (TwitterException e) {
     System.err.println("Error occurred while updating the status!");

    }

2.在按钮点击(无身份验证)

            String message="";
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(message)));
            startActivity(i);
于 2012-10-19T09:32:30.743 回答
0

请在您的清单文件中添加以下权限

<uses-permission android:name="android.permission.INTERNET"/>

也检查这个链接....

http://www.android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application

于 2012-10-19T09:32:31.350 回答