Last active
February 11, 2016 16:42
-
-
Save jforge/a7b97d373a57fb2e5d78 to your computer and use it in GitHub Desktop.
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
| HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); | |
| conn.setRequestMethod("GET"); | |
| int status = conn.getResponseCode(); | |
| boolean redirect = false; | |
| if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM | |
| || status == HttpURLConnection.HTTP_SEE_OTHER) { | |
| // redirect | |
| String newUrl = conn.getHeaderField("Location"); | |
| log.debug("Redirect " + url + " -> " + newUrl); | |
| redirect = true; | |
| conn = (HttpURLConnection) new URL(newUrl).openConnection(); | |
| conn.setRequestMethod("GET"); | |
| } | |
| status = conn.getResponseCode(); | |
| if (status == HttpURLConnection.HTTP_OK) { | |
| String encoding = null; | |
| if (conn.getContentEncoding() != null) { | |
| encoding = conn.getContentEncoding(); | |
| } else { | |
| encoding = "UTF-8"; | |
| } | |
| try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding))) { | |
| return br.readLine(); | |
| } | |
| } else { | |
| throw new IOException("connect failed: response-code: " + status); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment