import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** @author chaynes@indiana.edu */ public class GetText { private static final String DEFAULT_TEST_URL = "www.cs.indiana.edu/~chaynes/test.html"; private static final String DEFAULT_URL_PREFIX = "http://"; public static final int BUFFER_SIZE = 1000; public static final int EOF = -1; /** * @param url * syntax [http://[:][/[][?][#]] * * @return response to GET request on connection with given URL, or null if * the URL is malformed for there is a problem with the connection. */ public static String fromUrl(String url) { if (!url.startsWith(DEFAULT_URL_PREFIX)) url = DEFAULT_URL_PREFIX + url; try { HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setUseCaches(false); con.setRequestMethod("GET"); con.connect(); return readerToString(new InputStreamReader(con.getInputStream())); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } /** * @return contents of indicated text file in a string, or null if the * file cannot be found or there is an error while reading it. */ public static String fromFile(String fileName) { try { return readerToString(new FileReader(fileName)); } catch (FileNotFoundException e) { return null; } } private static String readerToString(Reader reader) { char[] buffer = new char[BUFFER_SIZE]; StringBuffer sb = new StringBuffer(); int numCharsRead; try { while ((numCharsRead = reader.read(buffer)) != EOF) { sb.append(buffer, 0, numCharsRead); } } catch (IOException e) { return null; } return sb.toString(); } /** * Usage: java GetText [url] where url defaults to * www.cs.indiana.edu/~chaynes/test.html and url prefix http:// is optional. * Prints server's response to url GET request. */ public static void main(String[] args) { String url; if (args.length == 1) { url = args[0]; } else if (args.length == 0) { url = DEFAULT_TEST_URL; } else { System.err.println("Usage: java Http [url]"); return; } String s = fromUrl(url); System.out.println(s); } }