可能重复:
Can we post image on twitter using twitter API in Android?
我在Android应用程序中工作,我想向Twitter发送一条消息和一张图片。我能够通过代码只发推特推文到推文:
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token, secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
**twitter.updateStatus("New tweet");**
twitter.//Which property of twitter should I use to tweet an image and //message
} catch (TwitterException e) {
// TODO Auto-generated catch block
Log.e("Errorssssssssssssss", e.toString());
}
我如何包含图片?
答案 0 :(得分:12)
参考http://www.londatiga.net/it/how-to-post-twitter-status-from-android/,使用twitter4j库
public void uploadPic(File file, String message) throws Exception {
try{
StatusUpdate status = new StatusUpdate(message);
status.setMedia(file);
mTwitter.updateStatus(status);}
catch(TwitterException e){
Log.d("TAG", "Pic Upload error" + e.getErrorMessage());
throw e;
}
}
其中mTwitter是Twitter类的实例
确保您使用的是最新版本的twitter4j-core jar文件。
答案 1 :(得分:2)
你可以试试Twitter4j Library附带的例子。以下代码将帮助你
public final class TwitpicImageUpload {
/**
* Usage: java twitter4j.examples.media.TwitpicImageUpload [API key] [message]
*
* @param args message
*/
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java twitter4j.examples.media.TwitpicImageUpload [API key] [image file path] [message]");
System.exit(-1);
}
try {
Configuration conf = new ConfigurationBuilder().setMediaProviderAPIKey(args[0]).build();
ImageUpload upload = new ImageUploadFactory(conf).getInstance(MediaProvider.TWITPIC);
String url;
if (args.length >= 3) {
url = upload.upload(new File(args[1]), args[2]);
} else {
url = upload.upload(new File(args[1]));
}
System.out.println("Successfully uploaded image to Twitpic at " + url);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to upload the image: " + te.getMessage());
System.exit(-1);
}
}
}
下载Twitter4j Library寻找更多示例。