Created
April 7, 2018 23:44
-
-
Save Bubblemelon/34cc86fe04ddaef5a594e07e2daea7c5 to your computer and use it in GitHub Desktop.
Fetching HTTP Request
This file contains 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
/** | |
* This method returns the entire result from the HTTP response. | |
* | |
* @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 { | |
// open http url connection object | |
// does not talk to network yet | |
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); | |
try { | |
// to read input contents | |
InputStream in = urlConnection.getInputStream(); | |
// tokenize streams | |
Scanner scanner = new Scanner(in); | |
// set delimiter to "\A" | |
// beginning of stream | |
// force scanner to read entire contents of stream into the next token stream | |
// this buffers data: | |
// pull data into small chunks | |
// http isnt required to give content size, code needs to be ready to handle different sizes | |
// allocates and deallocates when needed | |
// handles character encoding: translates UTF-8(default for json/javascript) to UTF-16 (default for Android) | |
// https://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string?page=1&tab=votes#tab-top | |
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