0

身份验证后尝试发推文时出现异常,推 特登录错误

if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData();

        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            Log.d("Inside","inside");
            String verifier = uri
                    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken accessToken = twitter.getOAuthAccessToken(
                        requestToken, verifier);

                // Shared Preferences
                Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET,
                        accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes

                Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);
                String username = user.getName();
                Log.d("usrnm",username);
                // Displaying in xml ui

            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }




private void loginToTwitter() {
        Log.d("user",""+isTwitterLoggedInAlready());
        // Check if already logged in
        if (!isTwitterLoggedInAlready()) {
            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();

            try {
                requestToken = twitter
                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);
                this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                        .parse(requestToken.getAuthenticationURL())));
            } catch (TwitterException e) {
                e.printStackTrace();
            } 
        } else {
            // user already logged into twitter    
            new updateTwitterStatus().execute("Hello");

        }
    }

堆栈跟踪

04-12 11:21:52.479: E/Twitter Login Error(1065): > null
4

1 回答 1

1

此解决方案用于通过 TwitPic API 将图像上传到 Twitter。您需要在他们的开发者部分注册您的帐户

我采用的解决方案可以被认为是一个两步解决方案。

首先,当用户点击发布按钮时,我首先抓取图片并上传到 TwitPic。从那里,我获取了 TwitPic ( String url = upload.upload(finalFile);) 返回的 URL。

在此代码的第二步中,在一个 String 实例 ( String finalStatusWithURL) 中,我获取了 an 的内容,EditText然后将步骤 1 中的 URL 附加到它上面。完成此操作后,该帖子最终发布到 Twitter。

Configuration conf = new ConfigurationBuilder()
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(twit_access_token)
.setOAuthAccessTokenSecret(twit_access_token_secret)
.setMediaProviderAPIKey(TWIT_PIC_API)
.build();

// SET THE FILE PATH (THIS IS UPDATED! NOTICE THE CHANGES MADE!!)
Uri tempUri = getImageUri(getApplicationContext(), bmpFinal);
File finalFile = new File(getRealPathFromURI(tempUri));

// THIS IS IMPORTANT. TWITPIC NEEDS THE ACTUAL / ABSOLUTE PATH OF THE IMAGE. JUST THE URI DOES NOT WORK!!!!

ImageUpload upload = new ImageUploadFactory(conf).getInstance(MediaProvider.TWITPIC);

String url = upload.upload(finalFile);
Log.e("TWITTER URL RESPONSE", url);

// END OF FIRST STEP:

// SECOND STEP IS TO UPLOAD TO TWITTER

ConfigurationBuilder builder = new ConfigurationBuilder();

builder.setOAuthConsumerKey(YOUR_TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(YOUR_TWITTER_CONSUMER_SECRET);

AccessToken accessToken = new AccessToken(your_twit_access_token, your_twit_access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

String finalStatusWithURL = null;

if (finalStatusMessage.trim().length() > 0) {

    finalStatusMessage = editStatusUpdate.getText().toString();
    finalStatusWithURL = finalStatusMessage + ":\n " + url;

} else {
    finalStatusWithURL = url;
}

twitter4j.Status response = twitter.updateStatus(finalStatusWithURL);
Log.e("TWITTER RESPONSE", response.getText());

这是获取您要上传的图像的真实路径的方法:

// HELPER METHOD TO GET REAL PATH FOR THE SELECTED IMAGE
public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    cursor.moveToFirst(); 
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(idx); 
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

更新:

在尝试上传之前执行此操作:

Bitmap bmpFinal = getBitmapFromURL("http://www.cosmopolitanclublahore.com/wp-content/uploads/2011/06/mexicanfoodrestaurant.jpg");

以及返回位图的方法:

// THE METHOD TO DOWNLOAD THE IMAGE INTO A BITMAP
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

你可能需要调整一些东西。我的代码使用用户从图库中选择的图像或他用相机拍摄的图像。您需要上传从 Internet 上获取的图像。里程可能会有所不同,并且可能需要调整代码。

于 2013-04-05T09:39:41.740 回答