Skip to content

Instantly share code, notes, and snippets.

@evaldeslacasa
Last active February 1, 2016 16:29
Show Gist options
  • Select an option

  • Save evaldeslacasa/d85110fee9fd93ea2a11 to your computer and use it in GitHub Desktop.

Select an option

Save evaldeslacasa/d85110fee9fd93ea2a11 to your computer and use it in GitHub Desktop.
Method to download file from URL in Java when the URL is redirected - statusCode = 301 resource temp moved
public static final File downloadColorImage(String colorUrlString){
File file = new File(System.getProperty( "catalina.base" ) + "/colorFile.png");
try {
URL colorUrl = new URL(colorUrlString);
HttpURLConnection huc = (HttpURLConnection)colorUrl.openConnection();
int statusCode = huc.getResponseCode(); //get response code
if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
|| statusCode == HttpURLConnection.HTTP_MOVED_PERM){ // if file is moved, then pick new URL
colorUrlString = huc.getHeaderField("Location");
colorUrl = new URL(colorUrlString);
huc = (HttpURLConnection)colorUrl.openConnection();
}
InputStream is = huc.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(file);
int i = 0;
while ((i = bis.read()) != -1)
fos.write(i);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
log.debug(colorUrlString);
return file;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment