如何使用twitter为我的jsp / java web项目实现登录

时间:2012-10-29 03:44:15

标签: java jsp twitter struts1

我在Struts1(Java框架)中创建了我的项目。我使用自定义登录表单进行登录/身份验证。但我的Boss希望用户使用Twitter帐户登录。就像在Stackoverflow中一样。

我通过从json请求调用Facebook Graph Api为Facebook做的相同类型的登录。但我对Twitter登录感到困惑。即使我阅读了twitter文档from here。还是很困惑。请帮助我。

2 个答案:

答案 0 :(得分:4)

您可以查看我的代码但您需要从twitter获取ConsumerKey,ConsumerSectret和accessToken

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class TwitterUtils {

public static void main(String[] args) {
    try {

        final String consumerKey = "**********";
        final String consumerSecret = "**********";
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        RequestToken requestToken = twitter.getOAuthRequestToken();

        String token = requestToken.getToken();
        String tokenSecret = requestToken.getTokenSecret();
        System.out.println("My token :: " + token);
        System.out.println("My token Secret :: " + tokenSecret);

        //AccessToken a = new AccessToken(token, tokenSecret);
        //twitter.setOAuthAccessToken(a);
        twitter.updateStatus("If you're reading this on Twitter, it worked!");

    } catch (TwitterException e) {
        e.printStackTrace();
    }
}//main
}/

答案 1 :(得分:0)

它需要在AsyncTask上下文中

final String consumerKey = "**********";
    final String consumerSecret = "*********";


    new AsyncTask<Void, Void, RequestToken>(){
        @Override
        protected RequestToken doInBackground(Void... voids) {
            try {
                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(consumerKey, consumerSecret);

                RequestToken requestToken = twitter.getOAuthRequestToken();
                return requestToken;
            } catch (TwitterException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(RequestToken requestToken) {
            super.onPostExecute(requestToken);
            if(requestToken == null)
                return;
            String token = requestToken.getToken();
            String tokenSecret = requestToken.getTokenSecret();
            Log.i("INFO", "My token :: " + token);
            Log.i("INFO", "My token Secret :: " + tokenSecret);
        }
    }.execute();