Last active
February 1, 2016 16:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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