-
-
Save anonymous/2463daf6bd6620241776 to your computer and use it in GitHub Desktop.
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
import java.*; | |
import java.net.*; | |
import java.io.*; | |
public class GetDataExample { | |
public static void main(String... args) { | |
if (args.length < 1) { | |
System.err.println("Usage: java GetDataExample <url>"); | |
System.exit(1); | |
} | |
String url = args[0]; | |
String data; | |
try { | |
data = notSoBadlyImplementedGetData(url); | |
System.out.println("Data: "); | |
System.out.println(data); | |
} catch (MalformedURLException mfue) { | |
System.err.println(url + " is an invalid URL."); | |
} catch (IOException ioe) { | |
System.err.println("Problem reading from url " + url + ". Check your network connection. Error message: " + ioe.getMessage()); | |
} | |
} | |
public static String notSoBadlyImplementedGetData(String urlAsString) throws MalformedURLException, IOException { | |
// Convert the string URL into a real URL | |
URL url = new URL(urlAsString); | |
// Open the connection to the server | |
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); | |
// Read the data from the connection | |
StringBuilder builder = new StringBuilder(); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
builder.append(line); | |
} | |
return builder.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment