Skip to content

Instantly share code, notes, and snippets.

@jkpr
Created January 30, 2018 22:22
Show Gist options
  • Save jkpr/3de753fb8dd7daa507a38484d43d8044 to your computer and use it in GitHub Desktop.
Save jkpr/3de753fb8dd7daa507a38484d43d8044 to your computer and use it in GitHub Desktop.
Java read return result from URL
/**
* This method returns the entire result from the HTTP response.
*
* See https://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment