Last active
October 14, 2017 03:47
-
-
Save nmschorr/d4d86ac6ba9fd6050d97a5d1c5efb650 to your computer and use it in GitHub Desktop.
The secret to easily reading a URL
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
static void readUrlData () throws Exception { | |
String builderLine; | |
String locUrlString = "http://jsonplaceholder.typicode.com/albums"; | |
System.out.println("\nRunning readUrlData"); | |
HttpURLConnection newUrlConn = (HttpURLConnection) new URL(locUrlString).openConnection(); | |
newUrlConn.setRequestMethod("GET"); | |
newUrlConn.setRequestProperty("Accept", "application/json"); | |
if (newUrlConn.getResponseCode() != HttpURLConnection.HTTP_OK) { | |
System.err.println("Can't connect to Webserver!"); | |
} | |
else System.out.println("Connected to Webserver!"); | |
InputStream is = newUrlConn.getInputStream(); | |
Reader bufReader = new BufferedReader(new InputStreamReader((is))); | |
StringBuilder myStrBuilder = new StringBuilder(); | |
while((builderLine = ((BufferedReader)bufReader).readLine()) != null) { | |
myStrBuilder.append(builderLine); | |
} | |
System.out.println("\\n" + myStrBuilder.toString()); | |
if(bufReader != null) bufReader.close(); | |
if(newUrlConn != null) newUrlConn.disconnect(); | |
out.println("\nDone with readUrlData "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment