Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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