在 Android 上使用 twitter4j 的问题

发布于 2024-12-06 03:46:11 字数 12921 浏览 0 评论 0原文

我正在使用 twitter4j 和 oauth-signpost 将 twitter 与我的 Android 应用程序集成。我已经实现了该活动的一部分,它所做的是对用户进行身份验证(或者至少这就是它应该做的)。问题是,它找不到令牌并给出此错误消息:

09-22 15:44:06.123: DEBUG/TwitterApp(363): Error getting access token
09-22 15:44:06.134: WARN/System.err(363): oauth.signpost.exception.OAuthExpectationFailedException: Request token or token secret not set in server reply. The service provider you use is probably buggy.
09-22 15:44:06.194: WARN/System.err(363):     at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:202)
09-22 15:44:06.194: WARN/System.err(363):     at oauth.signpost.AbstractOAuthProvider.retrieveAccessToken(AbstractOAuthProvider.java:97)
09-22 15:44:06.194: WARN/System.err(363):     at corp.encameo.app.TwitterApp$3.run(TwitterApp.java:139)

活动代码:

            public class TwitterActivity extends Activity {

                private TwitterApp mTwitter;

                private static final String twitter_consumer_key = "xxx";
                private static final String twitter_secret_key = "xxx";


                String FILENAME = "AndroidSSO_data";
                private SharedPreferences mPrefs;
                String name="";
                String bitly="";
                String imageLink="";

                EditText linkText;
                EditText descText;
                ImageButton backButton;

                public ImageLoader imageLoader; 

                @Override
                public void onCreate(Bundle savedInstanceState) {

                    super.onCreate(savedInstanceState);
                    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
                    setContentView(R.layout.twitter);
                    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title3);

                    TextView title=(TextView) findViewById(R.id.title_text_view_success3);
                    title.setText("Share on Twitter");

                    imageLoader=new ImageLoader(getApplicationContext());

                    linkText = (EditText) findViewById(R.id.twedit11);
                    descText = (EditText) findViewById(R.id.twedit22);

                    linkText.setFocusable(false);

                    mTwitter    = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);

                    mTwitter.setListener(mTwLoginDialogListener);

                    if (mTwitter.hasAccessToken()) 
                    {
                        String username = mTwitter.getUsername();
                        username        = (username.equals("")) ? "Unknown" : username;
                    }

                    else
                    {
                         mTwitter.authorize();
                    }




                    Bundle extras = getIntent().getExtras();
                    if(extras !=null) 
                    {
                        name = extras.getString("name");
                        bitly = extras.getString("bitly");
                        imageLink = extras.getString("imageLink");
                    }

                    if (bitly.equalsIgnoreCase(""))bitly="http://www.encameo.com";

                    linkText.setText(bitly);
                    linkText.setEnabled(false);

                    ImageView image=(ImageView) findViewById(R.id.twicon);

                    imageLoader.DisplayImage(imageLink, this, image);

                    Button twButton = (Button) findViewById(R.id.twButton);

                    twButton.setOnClickListener(new View.OnClickListener() {
                      public void onClick(View v){


                          finish();

                      }
                     });

                    backButton = (ImageButton) findViewById(R.id.back_button3);

                    backButton.setOnClickListener(new View.OnClickListener() 
                    {
                        public void onClick(View v)
                        {
                           System.out.println("!!! BACK !!!");
                           //finishActivity(0);
                           onBackPressed();
                        }
                    });
                }

                private final TwDialogListener mTwLoginDialogListener = new corp.encameo.app.TwitterApp.TwDialogListener() {
                    public void onComplete(String value) {
                        String username = mTwitter.getUsername();
                        username        = (username.equals("")) ? "No Name" : username;

                        Toast.makeText(TwitterActivity.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
                    }

                    public void onError(String value) {

                        Toast.makeText(TwitterActivity.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
                    }
                };


            }

TwitterApp 类:

            public class TwitterApp {
                private Twitter mTwitter;
                private TwitterSession mSession;
                private AccessToken mAccessToken;
                private CommonsHttpOAuthConsumer mHttpOauthConsumer;
                private OAuthProvider mHttpOauthprovider;
                private String mConsumerKey;
                private String mSecretKey;
                private ProgressDialog mProgressDlg;
                private TwDialogListener mListener;
                private Context context;

                public static final String CALLBACK_URL = "twitterapp://connect";
                private static final String TAG = "TwitterApp";

                public TwitterApp(Context context, String consumerKey, String secretKey) {
                    this.context    = context;

                    mTwitter        = new TwitterFactory().getInstance();
                    mSession        = new TwitterSession(context);
                    mProgressDlg    = new ProgressDialog(context);

                    mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);

                    mConsumerKey    = consumerKey;
                    mSecretKey      = secretKey;

                    mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
                    mHttpOauthprovider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token",
                                                                 "https://api.twitter.com/oauth/access_token",
                                                                 "https://api.twitter.com/oauth/authorize");

                    mAccessToken    = mSession.getAccessToken();

                    configureToken();
                }

                public void setListener(TwDialogListener listener) {
                    mListener = listener;
                }

                @SuppressWarnings("deprecation")
                private void configureToken() {
                    if (mAccessToken != null) {
                        mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);

                        mTwitter.setOAuthAccessToken(mAccessToken);
                    }
                }

                public boolean hasAccessToken() {
                    return (mAccessToken == null) ? false : true;
                }

                public void resetAccessToken() {
                    if (mAccessToken != null) {
                        mSession.resetAccessToken();

                        mAccessToken = null;
                    }
                }

                public String getUsername() {
                    return mSession.getUsername();
                }

                public void updateStatus(String status) throws Exception {
                    try {
                        mTwitter.updateStatus(status);
                    } catch (TwitterException e) {
                        throw e;
                    }
                }

                public void authorize() {
                    mProgressDlg.setMessage("Initializing ...");
                    mProgressDlg.show();

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

                            try {
                                authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);    

                                what = 0;

                                Log.d(TAG, "Request token url " + authUrl);
                            } catch (Exception e) {
                                Log.d(TAG, "Failed to get request token");

                                e.printStackTrace();
                            }

                            mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
                        }
                    }.start();
                }

                public void processToken(String callbackUrl)  {
                    mProgressDlg.setMessage("Finalizing ...");
                    mProgressDlg.show();

                    final String verifier = getVerifier(callbackUrl);

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

                            try {
                                mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);

                                mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());

                                configureToken();

                                User user = mTwitter.verifyCredentials();

                                mSession.storeAccessToken(mAccessToken, user.getName());

                                what = 0;
                            } catch (Exception e){
                                Log.d(TAG, "Error getting access token");

                                e.printStackTrace();
                            }

                            mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
                        }
                    }.start();
                }

                private String getVerifier(String callbackUrl) {
                    String verifier  = "";

                    try {
                        callbackUrl = callbackUrl.replace("twitterapp", "http");

                        URL url         = new URL(callbackUrl);
                        String query    = url.getQuery();

                        String array[]  = query.split("&");

                        for (String parameter : array) {
                             String v[] = parameter.split("=");

                             if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
                                 verifier = URLDecoder.decode(v[1]);
                                 break;
                             }
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }

                    return verifier;
                }

                private void showLoginDialog(String url) {
                    final TwDialogListener listener = new TwDialogListener() {
                        @Override
                        public void onComplete(String value) {
                            processToken(value);
                        }

                        @Override
                        public void onError(String value) {
                            mListener.onError("Failed opening authorization page");
                        }
                    };

                    new TwitterDialog(context, url, listener).show();
                }

                private Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        mProgressDlg.dismiss();

                        if (msg.what == 1) {
                            if (msg.arg1 == 1)
                                mListener.onError("Error getting request token");
                            else
                                mListener.onError("Error getting access token");
                        } else {
                            if (msg.arg1 == 1)
                                showLoginDialog((String) msg.obj);
                            else
                                mListener.onComplete("");
                        }
                    }
                };

                public interface TwDialogListener {
                    public void onComplete(String value);       

                    public void onError(String value);
                }
            }

任何建议???

I am using twitter4j and oauth-signpost for integrating twitter with my android app. I have implemented part of the activity, what it does is it authenticates the user (or atleast thats what its supposed to do). The problem is, it cant find the token and gives this error message:

09-22 15:44:06.123: DEBUG/TwitterApp(363): Error getting access token
09-22 15:44:06.134: WARN/System.err(363): oauth.signpost.exception.OAuthExpectationFailedException: Request token or token secret not set in server reply. The service provider you use is probably buggy.
09-22 15:44:06.194: WARN/System.err(363):     at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:202)
09-22 15:44:06.194: WARN/System.err(363):     at oauth.signpost.AbstractOAuthProvider.retrieveAccessToken(AbstractOAuthProvider.java:97)
09-22 15:44:06.194: WARN/System.err(363):     at corp.encameo.app.TwitterApp$3.run(TwitterApp.java:139)

activity code:

            public class TwitterActivity extends Activity {

                private TwitterApp mTwitter;

                private static final String twitter_consumer_key = "xxx";
                private static final String twitter_secret_key = "xxx";


                String FILENAME = "AndroidSSO_data";
                private SharedPreferences mPrefs;
                String name="";
                String bitly="";
                String imageLink="";

                EditText linkText;
                EditText descText;
                ImageButton backButton;

                public ImageLoader imageLoader; 

                @Override
                public void onCreate(Bundle savedInstanceState) {

                    super.onCreate(savedInstanceState);
                    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
                    setContentView(R.layout.twitter);
                    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title3);

                    TextView title=(TextView) findViewById(R.id.title_text_view_success3);
                    title.setText("Share on Twitter");

                    imageLoader=new ImageLoader(getApplicationContext());

                    linkText = (EditText) findViewById(R.id.twedit11);
                    descText = (EditText) findViewById(R.id.twedit22);

                    linkText.setFocusable(false);

                    mTwitter    = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);

                    mTwitter.setListener(mTwLoginDialogListener);

                    if (mTwitter.hasAccessToken()) 
                    {
                        String username = mTwitter.getUsername();
                        username        = (username.equals("")) ? "Unknown" : username;
                    }

                    else
                    {
                         mTwitter.authorize();
                    }




                    Bundle extras = getIntent().getExtras();
                    if(extras !=null) 
                    {
                        name = extras.getString("name");
                        bitly = extras.getString("bitly");
                        imageLink = extras.getString("imageLink");
                    }

                    if (bitly.equalsIgnoreCase(""))bitly="http://www.encameo.com";

                    linkText.setText(bitly);
                    linkText.setEnabled(false);

                    ImageView image=(ImageView) findViewById(R.id.twicon);

                    imageLoader.DisplayImage(imageLink, this, image);

                    Button twButton = (Button) findViewById(R.id.twButton);

                    twButton.setOnClickListener(new View.OnClickListener() {
                      public void onClick(View v){


                          finish();

                      }
                     });

                    backButton = (ImageButton) findViewById(R.id.back_button3);

                    backButton.setOnClickListener(new View.OnClickListener() 
                    {
                        public void onClick(View v)
                        {
                           System.out.println("!!! BACK !!!");
                           //finishActivity(0);
                           onBackPressed();
                        }
                    });
                }

                private final TwDialogListener mTwLoginDialogListener = new corp.encameo.app.TwitterApp.TwDialogListener() {
                    public void onComplete(String value) {
                        String username = mTwitter.getUsername();
                        username        = (username.equals("")) ? "No Name" : username;

                        Toast.makeText(TwitterActivity.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
                    }

                    public void onError(String value) {

                        Toast.makeText(TwitterActivity.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
                    }
                };


            }

TwitterApp class:

            public class TwitterApp {
                private Twitter mTwitter;
                private TwitterSession mSession;
                private AccessToken mAccessToken;
                private CommonsHttpOAuthConsumer mHttpOauthConsumer;
                private OAuthProvider mHttpOauthprovider;
                private String mConsumerKey;
                private String mSecretKey;
                private ProgressDialog mProgressDlg;
                private TwDialogListener mListener;
                private Context context;

                public static final String CALLBACK_URL = "twitterapp://connect";
                private static final String TAG = "TwitterApp";

                public TwitterApp(Context context, String consumerKey, String secretKey) {
                    this.context    = context;

                    mTwitter        = new TwitterFactory().getInstance();
                    mSession        = new TwitterSession(context);
                    mProgressDlg    = new ProgressDialog(context);

                    mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);

                    mConsumerKey    = consumerKey;
                    mSecretKey      = secretKey;

                    mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
                    mHttpOauthprovider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token",
                                                                 "https://api.twitter.com/oauth/access_token",
                                                                 "https://api.twitter.com/oauth/authorize");

                    mAccessToken    = mSession.getAccessToken();

                    configureToken();
                }

                public void setListener(TwDialogListener listener) {
                    mListener = listener;
                }

                @SuppressWarnings("deprecation")
                private void configureToken() {
                    if (mAccessToken != null) {
                        mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);

                        mTwitter.setOAuthAccessToken(mAccessToken);
                    }
                }

                public boolean hasAccessToken() {
                    return (mAccessToken == null) ? false : true;
                }

                public void resetAccessToken() {
                    if (mAccessToken != null) {
                        mSession.resetAccessToken();

                        mAccessToken = null;
                    }
                }

                public String getUsername() {
                    return mSession.getUsername();
                }

                public void updateStatus(String status) throws Exception {
                    try {
                        mTwitter.updateStatus(status);
                    } catch (TwitterException e) {
                        throw e;
                    }
                }

                public void authorize() {
                    mProgressDlg.setMessage("Initializing ...");
                    mProgressDlg.show();

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

                            try {
                                authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);    

                                what = 0;

                                Log.d(TAG, "Request token url " + authUrl);
                            } catch (Exception e) {
                                Log.d(TAG, "Failed to get request token");

                                e.printStackTrace();
                            }

                            mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
                        }
                    }.start();
                }

                public void processToken(String callbackUrl)  {
                    mProgressDlg.setMessage("Finalizing ...");
                    mProgressDlg.show();

                    final String verifier = getVerifier(callbackUrl);

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

                            try {
                                mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);

                                mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());

                                configureToken();

                                User user = mTwitter.verifyCredentials();

                                mSession.storeAccessToken(mAccessToken, user.getName());

                                what = 0;
                            } catch (Exception e){
                                Log.d(TAG, "Error getting access token");

                                e.printStackTrace();
                            }

                            mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
                        }
                    }.start();
                }

                private String getVerifier(String callbackUrl) {
                    String verifier  = "";

                    try {
                        callbackUrl = callbackUrl.replace("twitterapp", "http");

                        URL url         = new URL(callbackUrl);
                        String query    = url.getQuery();

                        String array[]  = query.split("&");

                        for (String parameter : array) {
                             String v[] = parameter.split("=");

                             if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
                                 verifier = URLDecoder.decode(v[1]);
                                 break;
                             }
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }

                    return verifier;
                }

                private void showLoginDialog(String url) {
                    final TwDialogListener listener = new TwDialogListener() {
                        @Override
                        public void onComplete(String value) {
                            processToken(value);
                        }

                        @Override
                        public void onError(String value) {
                            mListener.onError("Failed opening authorization page");
                        }
                    };

                    new TwitterDialog(context, url, listener).show();
                }

                private Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        mProgressDlg.dismiss();

                        if (msg.what == 1) {
                            if (msg.arg1 == 1)
                                mListener.onError("Error getting request token");
                            else
                                mListener.onError("Error getting access token");
                        } else {
                            if (msg.arg1 == 1)
                                showLoginDialog((String) msg.obj);
                            else
                                mListener.onComplete("");
                        }
                    }
                };

                public interface TwDialogListener {
                    public void onComplete(String value);       

                    public void onError(String value);
                }
            }

any suggestions ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文