6

如何在推特上上传图片/图片android sdk?我正在使用示例(twitpic),但它总是在这部分给出错误:

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

4 回答 4

2

你可以试试这个...

MainActivity.java

private static final String twitter_consumer_key = "Consumer key";
private static final String twitter_secret_key = "secret key";
TwitterApp mTwitter;

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
Bitmap bitmap;  // your image bitmap
    try{

    mTwitter = new TwitterApp(this, twitter_consumer_key, twitter_secret_key);
    }catch (Exception e) {

    }
upload_to_twitter.setOnClickListener(new OnClickListener() {

            @Override
    public void onClick(View v) {
            mTwitter.setListener(mTwLoginDialogListener);
            mTwitter.resetAccessToken();
            if (mTwitter.hasAccessToken() == true) {
                try {

                mTwitter.uploadPic(bitmap, "This is new pic");


                postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
                } catch (Exception e) {
        if (e.getMessage().toString().contains("duplicate")) {
                postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
                    }
                    e.printStackTrace();
                }
                mTwitter.resetAccessToken();
            } else {
                mTwitter.authorize();
            }
        }
    });

     }
}

TwitterApp.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.Toast;

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

public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://"
        + OAUTH_CALLBACK_HOST;

// public static final String CALLBACK_URL =
// "http://abhinavasblog.blogspot.com/";

static String base_link_url = "http://www.google.co.in/";
private static final String TWITTER_ACCESS_TOKEN_URL =       "https://api.twitter.com/oauth/access_token";
private static final String TWITTER_AUTHORZE_URL = "https://api.twitter.com/oauth/authorize";
private static final String TWITTER_REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public static final String MESSAGE = "MonkeySays";
        //+ "<a href= " + base_link_url + "</a>";
Message msg=new Message();
public TwitterApp(Activity 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);

    String request_url = TWITTER_REQUEST_URL;
    String access_token_url = TWITTER_ACCESS_TOKEN_URL;
    String authorize_url = TWITTER_AUTHORZE_URL;
    mHttpOauthprovider=new CommonsHttpOAuthProvider(request_url, access_token_url, authorize_url);
//      mHttpOauthprovider = new DefaultOAuthProvider(request_url,
//              access_token_url, authorize_url);
    mAccessToken = mSession.getAccessToken();

    configureToken();
}

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

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);
//          // File f = new File("/mnt/sdcard/74.jpg");
//          // mTwitter.updateProfileImage(f);
//      } catch (TwitterException e) {
//          throw e;
//      }
//  }

public void uploadPic(Bitmap file, String message)
        throws Exception {
    try {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey("your consumer key");
              builder.setOAuthConsumerSecret("your secret key")
        .setOAuthAccessToken(mHttpOauthConsumer.getToken())
  .setOAuthAccessTokenSecret(mHttpOauthConsumer.getTokenSecret());;
        Configuration configuration = builder.build();
        TwitterFactory twi=new TwitterFactory(configuration);
        Twitter twitter=twi.getInstance();
          ByteArrayOutputStream stream = new ByteArrayOutputStream();
            file.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
            StatusUpdate status = new StatusUpdate("Monkey Says");
            status.setMedia("newyear", bis);

        twitter.updateStatus(status);
    } catch (TwitterException e) {
        ///Log.d("TAG", "Pic Upload error" + e.getExceptionCode());
        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;
            } catch (Exception e) {
                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);
    int what = 1;

    try {
        mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);
        Toast.makeText(context, "new...", 87777).show();

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

        configureToken();

        User user = mTwitter.verifyCredentials();

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

        what = 0;
    } catch (Exception e) {
        e.printStackTrace();
    }

    mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
    new Thread() {
        @Override
        public void run() {



        }
    }.start();
}

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

    try {
        callbackUrl = callbackUrl.replace(OAUTH_CALLBACK_SCHEME, "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() {

        public void onComplete(String value) {
            processToken(value);
        }

        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);
}
}

TwitterDialog.java

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TwitterDialog extends Dialog {

static final float[] DIMENSIONS_LANDSCAPE = { 500, 300 };
static final float[] DIMENSIONS_PORTRAIT = { 300, 500 };
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT,
        ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private TwitterApp.TwDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private boolean progressDialogRunning = false;

public TwitterDialog(Context context, String url,TwitterApp.TwDialogListener listener) {
    super(context);

    mUrl = url;
    mListener = listener;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSpinner = new ProgressDialog(getContext());

    mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mSpinner.setMessage("Loading...");

    mContent = new LinearLayout(getContext());

    mContent.setOrientation(LinearLayout.VERTICAL);

    setUpTitle();
    setUpWebView();

    Display display = getWindow().getWindowManager().getDefaultDisplay();
    final float scale = getContext().getResources().getDisplayMetrics().density;
    float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT
            : DIMENSIONS_LANDSCAPE;

    addContentView(mContent, new FrameLayout.LayoutParams(
            (int) (dimensions[0] * scale + 0.5f), (int) (dimensions[1]
                    * scale + 0.5f)));
}

private void setUpTitle() {
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    Drawable icon = getContext().getResources().getDrawable(
            R.drawable.ic_launcher);

    mTitle = new TextView(getContext());

    mTitle.setText("Twitter");
    mTitle.setTextColor(Color.WHITE);
    mTitle.setTypeface(Typeface.DEFAULT_BOLD);
    mTitle.setBackgroundColor(0xFFbbd7e9);
    mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
    mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
    mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);

    mContent.addView(mTitle);
}

private void setUpWebView() {
    mWebView = new WebView(getContext());

    mWebView.setVerticalScrollBarEnabled(false);
    mWebView.setHorizontalScrollBarEnabled(false);
    mWebView.setWebViewClient(new TwitterWebViewClient());
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl(mUrl);
    mWebView.setLayoutParams(FILL);

    mContent.addView(mWebView);
}

private class TwitterWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith(TwitterApp.CALLBACK_URL)) {
            mListener.onComplete(url);

            TwitterDialog.this.dismiss();

            return true;
        } else if (url.startsWith("authorize")) {
            return false;
        }
        return true;
    }

    @Override
    public void onReceivedError(WebView view, int errorCode,
            String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        mListener.onError(description);
        TwitterDialog.this.dismiss();
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        mSpinner.show();
        progressDialogRunning = true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        String title = mWebView.getTitle();
        if (title != null && title.length() > 0) {
            mTitle.setText(title);
        }
        progressDialogRunning = false;
        mSpinner.dismiss();
    }

}

@Override
protected void onStop() {
    progressDialogRunning = false;
    super.onStop();
}

public void onBackPressed() {
    if(!progressDialogRunning){
        TwitterDialog.this.dismiss();
    }
}
}

TwitterSession.java

import twitter4j.auth.AccessToken;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;

public class TwitterSession {
private SharedPreferences sharedPref;
private Editor editor;

private static final String TWEET_AUTH_KEY = "";
private static final String TWEET_AUTH_SECRET_KEY = "";
private static final String TWEET_USER_NAME = "";
private static final String SHARED = "Twitter_Preferences";

public TwitterSession(Context context) {
    sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);

    editor = sharedPref.edit();
}

public void storeAccessToken(AccessToken accessToken, String username) {
    editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
    editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
    editor.putString(TWEET_USER_NAME, username);

    editor.commit();
}

public void resetAccessToken() {
    editor.putString(TWEET_AUTH_KEY, null);
    editor.putString(TWEET_AUTH_SECRET_KEY, null);
    editor.putString(TWEET_USER_NAME, null);

    editor.commit();
}

public String getUsername() {
    return sharedPref.getString(TWEET_USER_NAME, "");
}

public AccessToken getAccessToken() {
    String token = sharedPref.getString(TWEET_AUTH_KEY, null);
    String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);

    if (token != null && tokenSecret != null)
        return new AccessToken(token, tokenSecret);
    else
        return null;
}

}

用于此的jar文件..

路标核心1.2.1.2.jar

路标-commonshttp4-1.2.1.1.jar

twitter4j-core-3.0.3.jar

twitter4j-media-support-3.0.3.jar

这段代码非常有用,我只用这段代码在 twitter 上分享了这张图片。

如果发现有帮助,请接受答案..谢谢

于 2013-09-10T07:08:05.940 回答
1

尝试这个

             try {
        Configuration conf = new ConfigurationBuilder()                 
        .setOAuthConsumerKey(AppConstant.twitter_consumer_key) 
        .setOAuthConsumerSecret(AppConstant.twitter_secret_key) 
        .setOAuthAccessToken(AppConstant.twitterAccessToken.getToken()) 
        .setOAuthAccessTokenSecret(AppConstant.twitterAccessToken.getTokenSecret()) 
        .build(); 

        OAuthAuthorization auth = new OAuthAuthorization (conf, conf.getOAuthConsumerKey (), conf.getOAuthConsumerSecret (),
                new AccessToken (conf.getOAuthAccessToken (), conf.getOAuthAccessTokenSecret ()));

        ImageUpload upload = ImageUpload.getTwitpicUploader (AppConstant.twitpic_api_key, auth);

        Log.d(TAG, "Start sending image...");

        File picture = new File(AppConstant.rootFolder+File.separator+AppConstant.fileName); 

        url = upload.upload(picture);



        Log.d(TAG, "Image uploaded, Twitpic url is " + url);    
        Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(AppConstant.twitter_consumer_key, 
                AppConstant.twitter_secret_key,
                new AccessToken (AppConstant.twitterAccessToken.getToken(), AppConstant.twitterAccessToken.getTokenSecret()));
        if(status != null){
            twitter.updateStatus(status + " "+url);
        }else{
            twitter.updateStatus(url);
        }
        getDelegate().onRequestFinished(null);
    }catch (Exception e) {
        getDelegate().onRequestFailed(e);
        System.out.println("-------------------error|"+e.toString());
    }

更新

首先你需要在推特上创建一个应用程序

这是在 Twitter 上发布消息的代码

 ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
            configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
            configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
            configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
            Configuration configuration = configurationBuilder.build();
            final Twitter twitter = new TwitterFactory(configuration).getInstance();

            new Thread(new Runnable() {

                    private double x;

                    @Override
                    public void run() {
                            boolean success = true;
                            try {
                                    x = Math.random();
                                    twitter.updateStatus(message +" "+x);
                            } catch (TwitterException e) {
                                    e.printStackTrace();
                                    success = false;
                            }

                            final boolean finalSuccess = success;

                            callingActivity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                            postResponse.onFinsihed(finalSuccess);
                                    }
                            });

                    }
            }).start(); 

查看本教程以获取更多详细信息。

于 2013-03-14T06:59:30.173 回答
0

检查Android 的 SocialAuth。新版本可帮助您在 twitter 上上传图片以及获取提要和获取相册。

于 2013-03-14T10:42:39.777 回答
-1

我用它在 Twitpic 上分享照片。

private void hello() {
        // TODO Auto-generated method stub
        String url;

        long result = 0;

        String oth = prefs.getString(OAuth.OAUTH_TOKEN, "");
        String src = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

        Configuration conf = new ConfigurationBuilder()
                .setOAuthConsumerKey(Constants.CONSUMER_KEY)
                .setOAuthConsumerSecret(Constants.CONSUMER_SECRET)
                .setOAuthAccessToken(oth).setOAuthAccessTokenSecret(src)
                .build();

        OAuthAuthorization auth = new OAuthAuthorization(conf,
                conf.getOAuthConsumerKey(), conf.getOAuthConsumerSecret(),
                new AccessToken(conf.getOAuthAccessToken(),
                        conf.getOAuthAccessTokenSecret()));

        ImageUpload upload = ImageUpload.getTwitpicUploader(
                Constants.twitpic_api_key, auth);

        Log.d(main_genral_class.TAG, "Start sending image...");

        try {
            if (isFromCamera) {

                S_PHOTO_URL = S_PHOTO_URL.replace(" ", "%20");

                url = upload.upload(" ", new URL(S_PHOTO_URL).openStream(),
                        S_PHOTO_SMS);

            } else {

                Log.d("photo url twiter---->", S_PHOTO_URL);
                url = upload.upload(" ", new URL(S_PHOTO_URL).openStream(),
                        S_PHOTO_SMS);
            }
            result = 1;

            Log.d(main_genral_class.TAG, "Image uploaded, Twitpic url is "
                    + url);
        } catch (Exception e) {
            Log.e(main_genral_class.TAG, "Failed to send image");

            e.printStackTrace();
        }

    }

在此代码中 S_PHOTO_URL 是照片的 URL。

比如,S_PHOTO_URL = "http://www.thebiblescholar.com/android_awesome.jpg";

S_PHOTO_SMS = "你好,这是来自安卓应用!";

您还可以自定义代码并发送文件而不是 URL。

请试试这个,它肯定对你有帮助。

于 2012-10-05T07:07:03.127 回答