我发现一篇帖子是在推特发布之前发布的更新名为“在一条推文中发布多张照片”(我没有显示链接,因为我只允许显示两个名称少于10的链接)。
现在,这里是描述如何将多个图像附加到推文的Twitter API文档,唯一的问题是我不知道如何在Android中实现这一点:
https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
所以我想到了两个可能的解决方案 - 从Twitter4j库(https://github.com/yusuke/twitter4j/tree/master/twitter4j-media-support/src/main/java/twitter4j/media)修改其中一个方法,以允许多个图像附件或直接实现Twitter API文档。
任何想法如何做到这一点?
非常感谢输入!
答案 0 :(得分:0)
我使用twitter4j库在Android上分享了Twitter上的多个图像,它在twitter上分享多个单个图像工作正常
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
public class SharingActivity extends AppCompatActivity implements View.OnClickListener {
private static final String PREF_NAME = "sample_twitter_pref";
private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
private static final String PREF_KEY_TWITTER_LOGIN = "is_twitter_loggedin";
private static final String PREF_USER_NAME = "twitter_user_name";
private static final int WEBVIEW_REQUEST_CODE = 223;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private String consumerKey = null;
private String consumerSecret = null;
private String callbackUrl = null;
private String oAuthVerifier = null;
ImageView loginLayout,shareLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initTwitterConfigs();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
findViewById(R.id.twitBtnId).setOnClickListener(this);
findViewById(R.id.btn_share).setOnClickListener(this);
mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (isLoggedIn) {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
} else {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
}
}
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = twitter.showUser(userID);
String username = user.getName();
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.putString(PREF_USER_NAME, username);
e.commit();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
private void initTwitterConfigs() {
consumerKey = getString(R.string.twitter_consumer_key);
consumerSecret = getString(R.string.twitter_consumer_secret);
callbackUrl = getString(R.string.twitter_callback);
oAuthVerifier = getString(R.string.twitter_oauth_verifier);
}
private void loginToTwitter() {
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (!isLoggedIn) {
final ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
final Configuration configuration = builder.build();
final TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(callbackUrl);
final Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
}
}
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
if (responseCode == Activity.RESULT_OK) {
String verifier = data.getExtras().getString(oAuthVerifier);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("Twitter Login Failed", e.getMessage());
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.twitBtnId:
loginToTwitter();
break;
case R.id.btn_share:
new ShareImage().execute();
break;
}
}
public class ShareImage extends AsyncTask<Void,Void,String>{
@Override
protected void onPreExecute() {
//show progress here
super.onPreExecute();
}
@Override
protected String doInBackground(Void... voids) {
return uploadMultipleImages();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//hide progress here
Toast.makeText(SharingActivity.this,""+result,Toast.LENGTH_LONG).show();
}
}
public String uploadMultipleImages() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
try {
Bitmap bmp[] = {BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view2),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view3),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view4),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view5)};
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
long[] mediaIds = new long[4];
for (int i=0; i<4; i++) {
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp[i].compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
if (isCompres) {
UploadedMedia media = twitter.uploadMedia(tempFile);
mediaIds[i] = media.getMediaId();
tempFile.deleteOnExit();
}
}
StatusUpdate update = new StatusUpdate("test_name0");
update.setMediaIds(mediaIds);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
public String uploadSingleImage() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
try {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1);
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate update = new StatusUpdate("test_name0");
update.setMedia(tempFile);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
}
public class WebViewActivity extends Activity {
private WebView webView;
public static String EXTRA_URL = "extra_url";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
final String url = this.getIntent().getStringExtra(EXTRA_URL);
if (null == url) {
finish();
}
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(url);
}
class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String verifier = uri.getQueryParameter(getString(R.string.twitter_oauth_verifier));
Intent resultIntent = new Intent();
resultIntent.putExtra(getString(R.string.twitter_oauth_verifier), verifier);
setResult(RESULT_OK, resultIntent);
finish();
return true;
}
}
}
&#13;
运行以上代码请下载以下库并将其放入app libs文件夹并将其作为依赖项添加到gradle文件中
(1)twitter4j核-4.0.4.jar (2)twitter4j介质支撑-4.0.4.jar (3)twitter4j流-4.0.4.jar (4)路标-commonshttp4-1.2.1.1.jar (5)路标芯-1.2.1.1.jar (6)路标-jetty6-1.2.1.1.jar
工作正常,希望它对你也有帮助