Corrupted image when posting a tweet using spring framework twitter API
I am trying to publish a tweet with an embedded image from a Java Tomcat
server using the Spring framework's twitter API. The image is a JPG hosted
online (via Amazon Cloudfront CDN). I try to post using the updateTweet
function in the code snippet below:
import org.springframework.social.twitter.api.TweetData;
import org.springframework.social.twitter.api.TwitterProfile;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
// ...
public Tweet updateTweet(String accessToken, String accessTokenSecret,
String tweetMessage, String imageUrl){
TwitterTemplate twitter = new TwitterTemplate(twitterConsumerKey,
twitterConsumerSecret, accessToken, accessTokenSecret);
twitter.setRequestFactory(twitterHttpRequestFactory);
TweetData tweetData = new TweetData(tweetMessage);
try {
UrlResource imageUrlResource = new UrlResource(imageUrl);
logger.info("Trying to tweet image with url {} content length {}",
imageUrl, imageUrlResource.contentLength());
tweetData = tweetData.withMedia(imageUrlResource);
} catch(MalformedURLException e) {
logger.error("Malformed url for tweet image: {}", imageUrl);
} catch(IOException e) {
logger.error("IOException for tweet image {}\n{}", imageUrl, e);
}
return twitter.timelineOperations().updateStatus(tweetData);
}
The tweet posts to my user's timeline, and does include a JPG image with
the correct dimensions (640x640, like the source image) - however, the
actual image data is corrupted! Here is an example of the corrupted image
that ends up on my twitter timeline:
https://pbs.twimg.com/media/BVC5M5pCcAApIgP.jpg:large
My first thought was that the image data was being truncated somehow.
However, I've confirmed via the logger.info line in the code sample above
that the URLResource pointing at the image reports a content-length
matching the filesize of the original image.
I am unsure why this code is sending corrupted image data to twitter. I
have searched for working examples that post images to twitter using the
TweetData.withMedia function from Spring's framework, but I haven't been
able to find one.
No comments:
Post a Comment