是否可以使用Twitter4J在推文中上传多个图像?
我在官方文档上找不到任何内容。
感谢。
答案 0 :(得分:3)
您可以尝试以下内容,如果您要上传更多图像,可以使用循环或功能。
ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
twitterConfigBuilder.setDebugEnabled(true);
twitterConfigBuilder.setOAuthConsumerKey("consumerkey");
twitterConfigBuilder.setOAuthConsumerSecret("consumersecret");
twitterConfigBuilder.setOAuthAccessToken("accesstoken");
twitterConfigBuilder.setOAuthAccessTokenSecret("accesstokensecret");
Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
String statusMessage = "Hey I am posting 2 images of xyz event";
File imagefile1 = new File("/images/image_1.jpg");
File imagefile2 = new File("/images/image_2.jpg");
long[] mediaIds = new long[2];
UploadedMedia media1 = twitter.uploadMedia(imagefile1);
mediaIds[0] = media1.getMediaId();
UploadedMedia media2 = twitter.uploadMedia(imagefile2);
mediaIds[1] = media2.getMediaId();
StatusUpdate statusUpdate = new StatusUpdate(statusMessage);
statusUpdate.setMediaIds(mediaIds);
Status status = twitter.updateStatus(statusUpdate);
答案 1 :(得分:0)
UploadMultipleImages.java
package twitter4j.examples.tweets;
import java.io.File;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.UploadedMedia;
/**
* Example application that uploads multiple images.<br>
*
* @author Hiroaki TAKEUCHI - takke30 at gmail.com
*/
public final class UploadMultipleImages {
/**
* Usage: java twitter4j.examples.tweets.UploadMultipleImages [text] [file1] [file2] ...
*
* @param args message
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java twitter4j.examples.tweets.UploadMultipleImages [text] [file1] [file2] ...");
System.exit(-1);
}
try {
Twitter twitter = new TwitterFactory().getInstance();
long[] mediaIds = new long[args.length-1];
for (int i=1; i<args.length; i++) {
System.out.println("Uploading...[" + i + "/" + (args.length-1) + "][" + args[i] + "]");
UploadedMedia media = twitter.uploadMedia(new File(args[i]));
System.out.println("Uploaded: id=" + media.getMediaId()
+ ", w=" + media.getImageWidth() + ", h=" + media.getImageHeight()
+ ", type=" + media.getImageType() + ", size=" + media.getSize());
mediaIds[i-1] = media.getMediaId();
}
StatusUpdate update = new StatusUpdate(args[0]);
update.setMediaIds(mediaIds);
Status status = twitter.updateStatus(update);
System.out.println("Successfully updated the status to [" + status.getText() + "][" + status.getId() + "].");
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
System.exit(-1);
}
}
}