Skip to content

Instantly share code, notes, and snippets.

Created October 1, 2013 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2463daf6bd6620241776 to your computer and use it in GitHub Desktop.
Save anonymous/2463daf6bd6620241776 to your computer and use it in GitHub Desktop.
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