Skip to content

Instantly share code, notes, and snippets.

@nmschorr
Last active October 14, 2017 03:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nmschorr/d4d86ac6ba9fd6050d97a5d1c5efb650 to your computer and use it in GitHub Desktop.
The secret to easily reading a URL
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