Search code examples
androidimagetwittertwitter4j

Android twitter4j - how to share remote image?


I have successfully set up twitter4j and can now post text updates and also upload local media from the device to twitter. But what I really need to do is share remote images from the web - e.g., http://example.com/image.png.

When I execute this code... StatusUpdate statusUpdate = new StatusUpdate("Hello Twitter"); String imageUrl = "http://example.com/image.png"; File file = new File(imageUrl); statusUpdate.setMedia(file); twitter4j.Status status = twitter.updateStatus(statusUpdate);

...it looks like twitter4j tries to treat the url as local because it appears to put a / in front of it, and then throws an exception saying... /http://example.com/image.png: open failed: ENOENT (No such file or directory)

How to solve? Thanks.


Solution

  • I found there is another setMedia() method that accepts an inputstream as one of it's parameters. This inputstream can be linked to a remote image, like this...

    StatusUpdate statusUpdate = new StatusUpdate("Hello Twitter");
    String imageUrl = "http://example.com/image.png";
    URL url = new URL(imageUrl);
    URLConnection urlConnection = url.openConnection();
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    statusUpdate.setMedia("image.png", in);
    twitter4j.Status status = twitter.updateStatus(statusUpdate);
    //might be a good idea to close the inputstream in a finally block