我正在尝试使用Twitter API在Android应用程序中实现图片上传功能。我看到了很多例子,例如:
private void uploadImage(File imagefile, final String tweettext){
TypedFile typedFile = new TypedFile("image/*", imagefile);
TwitterApiClient twitterApiClient = new TwitterApiClient(twitterSession);
MediaService mediaservice = twitterApiClient.getMediaService();
mediaservice.upload(typedFile, null, null, new Callback<Media>() {
@Override
public void success(Result<Media> result) {
postTweet(tweettext, result.data.mediaIdString);
tweetMediaFile = null;
iv1.setImageDrawable(null);
}
@Override
public void failure(TwitterException e) {
Toast.makeText(MainActivity.this, "Medienupload fehlgeschlagen. Bitte erneut versuchen.", Toast.LENGTH_SHORT).show();
}
});
}
但是由于在新版本的Twitter API中,MediaService.upload的另一个参数(RequestBody,RequestBody,RequestBody),我正在尝试这样做:
private void uploadImage(File imagefile, final String tweettext) throws IOException {
RequestBody rb = RequestBody.create(MediaType.parse("image/*"), imagefile);
TwitterApiClient twitterApiClient = new TwitterApiClient(twitterSession);
MediaService mediaservice = twitterApiClient.getMediaService();
Response<Media> uploadResponse = mediaservice.upload(rb, null, null).execute();
if (uploadResponse.isSuccessful()) {
postTweet(tweettext, uploadResponse.body().mediaIdString);
tweetMediaFile = null;
iv1.setImageDrawable(null);
} else {
Toast.makeText(TweetPostActivity.this, "Medienupload fehlgeschlagen. Bitte erneut versuchen.",
Toast.LENGTH_SHORT).show();
}
}
它对我不起作用-响应(mediaIdString
)中的uploadResponse.body().mediaIdString
为空。任何想法我做错了吗?感谢您的帮助。