【问题标题】:setOauthAccessToken - twitter4j - AndroidStudio获取 Oauth 访问令牌 - twitter4j - Android Studio
【发布时间】:2015-09-07 08:12:30
【问题描述】:

我的应用上有这个方法:

@SuppressWarnings("deprecation")
void displayTimeLine(String token, String secret) {
    if (null != token && null != secret) {
        List<Status> statuses = null;
        try {
            twitter.setOAuthAccessToken(token, secret);
            statuses = twitter.getUserTimeline();
            Toast.makeText(this, statuses.get(0).getText(), Toast.LENGTH_LONG)
                .show();
        } catch (Exception ex) {
            Toast.makeText(this, "Error:" + ex.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.d("Main.displayTimeline",""+ex.getMessage());
        }

    } else {
        Toast.makeText(this, "Not Verified", Toast.LENGTH_LONG).show();
    }
}

它会抛出这个错误:

Error:(106, 12) error: method setOAuthAccessToken in interface   OAuthSupport cannot be applied to given types;
required: AccessToken
found: String,String
reason: actual and formal argument lists differ in length

我正在导入一个基于 Eclipse 的项目(旧的 twitter4j 示例),我不得不更改这些导入:

import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

收件人:

import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

这是完整的课程:

package com.aman.samples.t4jsignin;

import java.util.List;

import com.aman.t4j.activities.R;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.Toast;

public class Main extends Activity {
/** Called when the activity is first created. */

Twitter twitter;
RequestToken requestToken;
//Please put the values of consumerKy and consumerSecret of your app 
public final static String consumerKey = "removed"; // "your key here";
public final static String consumerSecret = "removed"; // "your secret key here";
private final String CALLBACKURL = "T4J_OAuth://callback_main";  //Callback URL that tells the WebView to load this activity when it finishes with twitter.com. (see manifest)


/*
 * Calls the OAuth login method as soon as its started
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    OAuthLogin();
}

/*
 * - Creates object of Twitter and sets consumerKey and consumerSecret
 * - Prepares the URL accordingly and opens the WebView for the user to provide sign-in details
 * - When user finishes signing-in, WebView opens your activity back
 */
void OAuthLogin() {
    try {
        twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
        String authUrl = requestToken.getAuthenticationURL();
        this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                .parse(authUrl)));
    } catch (TwitterException ex) {
        Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
        Log.e("in Main.OAuthLogin", ex.getMessage());
    }
}


/*
 * - Called when WebView calls your activity back.(This happens when the user has finished signing in)
 * - Extracts the verifier from the URI received
 * - Extracts the token and secret from the URL 
 */
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Uri uri = intent.getData();
    try {
        String verifier = uri.getQueryParameter("oauth_verifier");
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,
                verifier);
        String token = accessToken.getToken(), secret = accessToken
                .getTokenSecret();
        displayTimeLine(token, secret); //after everything, display the first tweet 

    } catch (TwitterException ex) {
        Log.e("Main.onNewIntent", "" + ex.getMessage());
    }

}

/*
 * Displays the timeline's first tweet in a Toast
 */

@SuppressWarnings("deprecation")
void displayTimeLine(String token, String secret) {
    if (null != token && null != secret) {
        List<Status> statuses = null;
        try {
            twitter.setOAuthAccessToken(token, secret);
            statuses = twitter.getUserTimeline();
            Toast.makeText(this, statuses.get(0).getText(), Toast.LENGTH_LONG)
                .show();
        } catch (Exception ex) {
            Toast.makeText(this, "Error:" + ex.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.d("Main.displayTimeline",""+ex.getMessage());
        }

    } else {
        Toast.makeText(this, "Not Verified", Toast.LENGTH_LONG).show();
    }
  }
}

【问题讨论】:

    标签: android eclipse twitter android-studio twitter4j


    【解决方案1】:

    您可能想尝试更新的库(我不确定您的版本)。

    注意:在公共网站上发帖时,您应该始终删除您的消费者和消费者密钥。 (:

    在你的 onCreate 方法中,添加这个

        twitter = new TwitterFactory().getInstance();
    
        twitter.setOAuthConsumer("Consumer Key", "Consumer Secret");
    

    要调用我的 tokenGet 类,

      new TokenGet().execute();
    

    还有tokenGet方法

        private class TokenGet extends AsyncTask<String, String, String> {
    
        @Override
        protected String doInBackground(String... args) {
    
            try {
                requestToken = twitter.getOAuthRequestToken();
                oauth_url = requestToken.getAuthorizationURL();
            } catch (TwitterException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return oauth_url;
        }
        @Override
        protected void onPostExecute(String oauth_url) {
            if(oauth_url != null){
                Log.e("URL", oauth_url);
                auth_dialog = new Dialog(getActivity());
                auth_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    
                auth_dialog.setContentView(R.layout.auth_dialog);
                web = (WebView)auth_dialog.findViewById(R.id.webv);
                web.getSettings().setJavaScriptEnabled(true);
                web.loadUrl(oauth_url);
                web.setWebViewClient(new WebViewClient() {
                    boolean authComplete = false;
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon){
                        super.onPageStarted(view, url, favicon);
                    }
    
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        if (url.contains("oauth_verifier") && authComplete == false){
                            authComplete = true;
                            Log.e("Url",url);
                            Uri uri = Uri.parse(url);
                            oauth_verifier = uri.getQueryParameter("oauth_verifier");
    
                            auth_dialog.dismiss();
                            new AccessTokenGet().execute();
                        }else if(url.contains("denied")){
                            auth_dialog.dismiss();
                            Toast.makeText(getActivity(), "Sorry !, Permission Denied", Toast.LENGTH_SHORT).show();
    
    
                        }
                    }
                });
                auth_dialog.show();
                auth_dialog.setCancelable(true);
    
    
    
            }else{
    
                Toast.makeText(getActivity(), "Sorry !, Network Error or Invalid Credentials", Toast.LENGTH_SHORT).show();
    
    
            }
        }
    }
    
    private class AccessTokenGet extends AsyncTask<String, String, Boolean> {
    
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progress = new ProgressDialog(getActivity());
            progress.setMessage("Fetching Data ...");
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.setIndeterminate(true);
            progress.show();
    
        }
    
    
        @Override
        protected Boolean doInBackground(String... args) {
    
            try {
    
    
                accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
                SharedPreferences.Editor edit = pref.edit();
                edit.putString("ACCESS_TOKEN", accessToken.getToken());
                edit.putString("ACCESS_TOKEN_SECRET", accessToken.getTokenSecret());
    
                edit.commit();
    
    
            } catch (TwitterException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
    
    
            }
    
            return true;
        }
        @Override
        protected void onPostExecute(Boolean response) {
            if(response){
                Intent i = new Intent(getActivity(),MainMenu.class);
    

    在此处获取您的访问令牌

                i.putExtra("ACCESS_TOKEN", accessToken.getToken());
                i.putExtra("ACCESS_TOKEN_SECRET", accessToken.getTokenSecret());
                startActivity(i);
            }
        }
    
    
    }
    

    我正在使用 4.0.3 版本的 twitter4j。这适用于我的情况。 我从一些教程网站上拿了它,但我现在不记得网址了。

    【讨论】:

    • 对于 consumerkeys 大声笑,对。是的,让我试试@Gene 谢谢(:
    • 如果你想使用回调,记得在apps.twitter.com创建一个应用程序。对于回调 url,任何 url 都可以。请记住为回调 url 添加 http:// 或 https://。我正在使用 http://
    • @NeoVe 我为 onCreate 部分添加了一些缺失的代码。
    • 谢谢,我马上试试,抱歉耽搁了
    • @NeoVe np。很高兴我能帮上忙!
    猜你喜欢
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    相关资源
    最近更新 更多