0

Im trying to download an image from the following url in java: http://placehold.it/600/24f355

if you follow the url above you will see a placeholder image.

the url that official holds the image is https://placeholdit.imgix.net/~text?txtsize=56&bg=24f355&txt=600%C3%97600&w=600&h=600

Note: Please note that i only have direct access to the first URL. The final url i have no way to know apart from following the first url manually through a browser

I've tried multiple ways to download this image but none of them were successfull.

The code i have at the moment that is expected to download the image is the following:

(The code downloads a image that cannot be opened..)

     public void saveImage(String imageUrl, String path) {
        // This method only saves the "dummy" image
        try{
            URL url = new URL(imageUrl);
            InputStream is = url.openStream();
            OutputStream os = new FileOutputStream(path);

            byte[] b = new byte[2048];
            int length;

            while ((length = is.read(b)) != -1) {
                os.write(b, 0, length);
            }

            is.close();
            os.close();
        }catch(IOException e){
            e.printStackTrace();
        }

    }   
}

the function receives the image url which is the one i refered at the top and specifies a path on the system where the image will be saved.

What am i doing wrong?

Your help would be awesome! Thanks in advance

MK1000
  • 23
  • 2
  • 7
  • possible answer? http://stackoverflow.com/questions/5882005/how-to-download-image-from-any-web-page-in-java – Ben Arnao Jan 26 '17 at 21:13
  • i don think so, i've been over this for a day now. I think the problem is that the url that i give to the function is not the "official" url of the image @BenArnao – MK1000 Jan 26 '17 at 21:20
  • why don't you give it the official url then? – Ben Arnao Jan 26 '17 at 21:22
  • i only have access to the http://placehold.it/600/24f355 url. the other one i dont know. i only know if i follow it manually through chrome @BenArnao – MK1000 Jan 26 '17 at 21:25
  • Possible duplicate of [URLConnection Doesn't Follow Redirect](http://stackoverflow.com/questions/1884230/urlconnection-doesnt-follow-redirect) – shmosel Jan 26 '17 at 21:43

1 Answers1

1
String finalURL(String url) {
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setInstanceFollowRedirects(false);
    con.connect();
    return con.getHeaderField("Location").toString();
}
Ben Arnao
  • 492
  • 5
  • 11