Skip to content

Instantly share code, notes, and snippets.

Last active October 14, 2017 03:47
What would you like to do?
The secret to easily reading a URL
static void readUrlData () throws Exception {
String builderLine;
String locUrlString = "";
System.out.println("\nRunning readUrlData");
HttpURLConnection newUrlConn = (HttpURLConnection) new URL(locUrlString).openConnection();
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) {
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