Skip to content

Instantly share code, notes, and snippets.

@jforge
Last active February 11, 2016 16:42
Show Gist options
  • Select an option

  • Save jforge/a7b97d373a57fb2e5d78 to your computer and use it in GitHub Desktop.

Select an option

Save jforge/a7b97d373a57fb2e5d78 to your computer and use it in GitHub Desktop.
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