【问题标题】:How to post picture on Twitter from android application using Twitter4j如何使用 Twitter4j 从 Android 应用程序在 Twitter 上发布图片
【发布时间】:2012-09-20 01:22:22
【问题描述】:

我见过this answer 提出相同类型的问题。当我使用代码时,它总是抛出一个Twitter Exception。我把它称为upload_twic_pic(new File("my_image_path"));

并关注Exception

W/System.err(2195): Connection reset by peerRelevant discussions can be on the Internet at:
W/System.err(2195):     http://www.google.co.jp/search?q=ea09dc6d or
W/System.err(2195):     http://www.google.co.jp/search?q=050d9b43
W/System.err(2195): TwitterException{exceptionCode=[ea09dc6d-050d9b43 0237e8c8-9ca5c8e4], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.3}
W/System.err(2195):     at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:204)

【问题讨论】:

标签: android twitter twitter4j image-upload


【解决方案1】:

找到了答案here,它的作用就像魅力一样。只需复制并粘贴答案中提供的代码,并使用旧的 jar 文件,我按照答案中的说明将其替换为最新的。

【讨论】:

    【解决方案2】:

    使用SocialAuth Android library在 Twitter/Facebbok 上上传图片非常简单

    【讨论】:

      【解决方案3】:
      public class MainActivity extends Activity {
          // Constants
          /**
           * Register your here app https://dev.twitter.com/apps/new and get your
           * consumer key and secret
           * */
          static String TWITTER_CONSUMER_KEY = "uTMokDQHlUP8rjl6LEmgjg"; // place your cosumer key here
          static String TWITTER_CONSUMER_SECRET = "xrI8yw6QBKa0ny7N4Nru01JiX4sIThsxzGV4MJ3YOUY"; // place your consumer secret here
      
          // Preference Constants
          static String PREFERENCE_NAME = "twitter_oauth";
          static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
          static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
          static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
      
          static final String TWITTER_CALLBACK_URL = "hello://sample";
      
          // Twitter oauth urls
          static final String URL_TWITTER_AUTH = "auth_url";
          static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
          static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
      
          // Login button
          Button btnLoginTwitter;
      
      
          // Progress dialog
          ProgressDialog pDialog;
      
          // Twitter
          private static Twitter twitter;
          private static RequestToken requestToken;
      
          // Shared Preferences
          private static SharedPreferences mSharedPreferences;
      
      
      
          // Alert Dialog Manager
          AlertDialogManager alert = new AlertDialogManager();
      
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      
              cd = new ConnectionDetector(getApplicationContext());
      
      
      
      
              // All UI elements
              btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
      
      
              // Shared Preferences
              mSharedPreferences = getApplicationContext().getSharedPreferences(
                      "MyPref", 0);
      
              /**
               * Twitter login button click event will call loginToTwitter() function
               * */
              btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
      
                  @Override
                  public void onClick(View arg0) {
                      // Call login twitter function
                      loginToTwitter();
                  }
              });
      
      
      
      
              if (!isTwitterLoggedInAlready()) {
                  Uri uri = getIntent().getData();
                  if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
                      // oAuth verifier
                      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());
      
      
      
                          // Getting user details from twitter
                          // For now i am getting his name only
                          long userID = accessToken.getUserId();
                          User user = twitter.showUser(userID);
                          String username = user.getName();
      
      
                      } catch (Exception e) {
                          // Check log for login errors
                          Log.e("Twitter Login Error", "> " + e.getMessage());
                      }
                  }
              }
      
          }
      
          /**
           * Function to login twitter
           * */
          private void loginToTwitter() {
              // 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 {
      
                  new updateTwitterStatus().execute("helloooo");
      
              }
          }
      
          /**
           * Function to update status
           * */
          class updateTwitterStatus extends AsyncTask<String, String, String> {
      
              /**
               * Before starting background thread Show Progress Dialog
               * */
              @Override
              protected void onPreExecute() {
                  super.onPreExecute();
                  pDialog = new ProgressDialog(MainActivity.this);
                  pDialog.setMessage("Updating to twitter...");
                  pDialog.setIndeterminate(false);
                  pDialog.setCancelable(false);
                  pDialog.show();
              }
      
              /**
               * getting Places JSON
               * */
              protected String doInBackground(String... args) {
                  //Log.d("Tweet Text", "> " + args[0]);
                  String status = args[0];
                  try {
                      ConfigurationBuilder builder = new ConfigurationBuilder();
                      builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                      builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
      
                      // Access Token 
                      String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
                      // Access Token Secret
                      String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
      
                      AccessToken accessToken = new AccessToken(access_token, access_token_secret);
      
                      Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
      
                      // Update status
      
                      StatusUpdate ad=new StatusUpdate("RaagFm");
      
      
      
                      // The InputStream opens the resourceId and sends it to the buffer
                      InputStream is = getResources().openRawResource(R.raw.icon);
      
                      ad.setMedia("RaagFm",is);
      
                      twitter4j.Status response = twitter.updateStatus(ad);
      
      
      
                      Log.d("Status", "> " + response.getText());
                  } catch (TwitterException e) {
                      // Error in updating status
                      Log.d("Twitter Update Error", e.getMessage());
                  }
                  return null;
              }
      
              /**
               * After completing background task Dismiss the progress dialog and show
               * the data in UI Always use runOnUiThread(new Runnable()) to update UI
               * from background thread, otherwise you will get error
               * **/
              protected void onPostExecute(String file_url) {
                  // dismiss the dialog after getting all products
                  pDialog.dismiss();
                  // updating UI from Background Thread
                  runOnUiThread(new Runnable() {
                      @Override
                      public void run() {
                          Toast.makeText(getApplicationContext(),
                                  "Status tweeted successfully", Toast.LENGTH_SHORT)
                                  .show();
      
                      }
                  });
              }
      
          }
      
      
      
      
          private boolean isTwitterLoggedInAlready() {
              // return twitter login status from Shared Preferences
              return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
          }
      
          protected void onResume() {
              super.onResume();
          }
      
      }
      

      【讨论】:

        【解决方案4】:

        这对我来说就像一个魅力.. 用于发布带有文字的图片.. 希望这会对某人有所帮助 https://github.com/learnNcode/DemoTwitterImagePost 谢谢

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-11
          • 2019-06-05
          • 1970-01-01
          • 1970-01-01
          • 2014-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多