The secret to easily reading a URL
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
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