Reputation: 23
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
Upvotes: 0
Views: 3084
Reputation: 543
String finalURL(String url) {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setInstanceFollowRedirects(false);
con.connect();
return con.getHeaderField("Location").toString();
}
Upvotes: 1