Twitter4j在安卓上无法正常使用Twitter。

8

我正在使用twitter4j将Twitter集成到Android中。这是我的Twitter代码,我正在为Twitter创建单独的类。

我查看了与此类似的问题,但没有任何解决方法适用于我。 问题以及其他一些问题。

Twitter类

public class OBLTwitter {

private static final String TAG = "OBLTwitter";
private Activity activity;

// Twitter constants
private static final String TWITTER_CONSUMER_KEY = "KEY";
private static final String TWITTER_CONSUMER_SECRET = "SECRET";
public static final String TWITTER_CALLBACK_URL = "app://ridesharebuddy";

// Twitter variables
private static Twitter twitter;
private static RequestToken requestToken;
public static boolean userDeniedToContinue;

    public OBLTwitter(Activity activity) {

        Log.d(TAG, "Parameterized constructor called.");

        this.activity = activity;
        userDeniedToContinue = false;
    }


    // Login to twitter
    public void loginToTwitter() {

        Log.e(TAG, "Logging in to twitter.");

        if(!isNetworkAvailable(this.activity))
        {
            Log.e(TAG, "Interent connection not available");
        }

        // Set up Twitter object
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    if(twitter == null)
                    {
                        Log.e(TAG, "twitter is null");
                    }
                    Log.e("called", "called run method");
                    // Get RequestToken and call authentication URL to show
                    // twitter page
                    requestToken = twitter
                            .getOAuthRequestToken(TWITTER_CALLBACK_URL);

                    Log.e(TAG, "getting request token");

                    Log.e("oAuth token :", requestToken.getToken());
                    Log.e("oAUth secret:", requestToken.getTokenSecret());
                    Log.e("oAuth URL: ", requestToken.getAuthenticationURL());

                     activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                     .parse(requestToken.getAuthenticationURL())));

                } catch (TwitterException te) {

                    Log.e(TAG, "Twitter exception, Login error.");
                    te.printStackTrace();                       

                    Log.e(TAG, "Error code : " + te.getErrorCode());
                    Log.e(TAG, "Error message : " + te.getErrorMessage());
                    Log.e(TAG, "Status code : " + te.getStatusCode());
                    Log.e(TAG, "Access level : " + te.getAccessLevel());

                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
        });

        thread.start();
    }

    public boolean isNetworkAvailable(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

这是我的活动代码,我从这里调用loginToTwitter函数。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    OBLTwitter twitter = new OBLTwitter(this);
    twitter.loginToTwitter();
}

这是我的清单文件,我添加它是因为我根据不同问题的回答者提供的建议做了一些更改。

 <uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.objectlounge.OBLTwitter.MainActivity"
        android:label="@string/app_name" >
        android:launchMode="singleInstance">


        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="ridesharebuddy"
                android:scheme="app" />
        </intent-filter>
    </activity>
</application>

错误日志

示例图片


我在这里发布了一些很好的示例代码,链接为https://github.com/ericwoodruff/android_twitter_oauth。 - Eric Woodruff
谢谢这个。我下载了它作为参考。我尝试运行它,但在onActivityResult中出现错误。它进入了switch部分的取消块,然后崩溃了。它没有显示登录并显示已取消。 - keen
它可能会假设您已经创建了一个 twitter4j.properties 文件,并将其与您的密钥一起放在类路径中。http://twitter4j.org/en/configuration.html - Eric Woodruff
我已经删除了它,但仍然存在相同的问题。 - keen
请查看此链接:http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/,它会对您有很大的帮助。 - Hitesh Singh
你尝试在loginToTwitter()方法中启动的是哪个活动? - Roman Black
5个回答

6
您收到的 HTTP 403(禁止)状态码很可能是因为Twitter最近已将其流量限制为仅支持TLS。根据Twitter API更改历史记录,从2014年1月14日起,api.twitter.com仅支持TLS通信。许多默认使用普通HTTP的库已进行更新以遵循此规定,Twitter4j 版本3.0.5也是如此,现在默认情况下使用TLS。
如果您真的不想更新该库,但仍希望使用当前版本,则可以通过对代码进行轻微更改来实现。 ConfigurationBuilder 类有一个名为setSSL方法,您可以将其设置为true以使用HTTPS。因此,您可以通过向代码添加以下行来使其正常工作:
builder.setSSL(true);

1
"

状态码 403 错误表示您的登录存在问题。

  • 请检查您是否已成功在 dev.twitter.com 上创建了一个应用程序
  • 确保在正确的位置使用了正确的密钥
  • 您的用户名/密码是否正确
  • 最后,请确认您正在使用最新版本的 Twitter4J? 确保它仅使用 HTTP*S* URL。
"

1

0

试试这个:

mTwitter = new TwitterFactory().getInstance();

mHttpOauthConsumer = new CommonsHttpOAuthConsumer(twitterConsumerKey, twitterSecretKey);
mHttpOauthprovider = new CommonsHttpOAuthProvider("https://twitter.com/oauth/request_token",
        "https://twitter.com/oauth/access_token",
        "https://twitter.com/oauth/authorize");

try{
    authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);
}catch(OAuthCommunicationException oACEx){
    Log.d("", "");
}catch(OAuthMessageSignerException oAMSEx){
    Log.d("", "");
}catch(OAuthNotAuthorizedException oANAEx){
    Log.d("", "");
}catch(OAuthExpectationFailedException oAEFEx){
    Log.d("", "");
}

但是你需要将一些jar库添加到你的项目中:

https://code.google.com/p/oauth-signpost/downloads/detail?name=signpost-core-1.2.1.1.jar&can=2&q=

https://code.google.com/p/oauth-signpost/downloads/detail?name=signpost-commonshttp4-1.2.1.1.jar&can=2&q=

https://code.google.com/p/oauth-signpost/downloads/detail?name=signpost-jetty6-1.2.1.1.jar&can=2&q=


0

只需将您的 Twitter jar 更新为最新版本即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接