import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class URLReader { /** * This method sends a GET request for the item at a specified URL, the prints the * response. Note that the approach used to read the response assumes that the item * is text and not binary data like a .jpg. If there's a command-line argument to * the program it's used as the URL, otherwise we fetch the author's page from the * first Wireshark lab. * * @author brichards */ public static void main(String[] args) throws Exception { String urlString = "http://gaia.cs.umass.edu/wireshark-labs/INTRO-wireshark-file1.html"; if (args.length > 0) { urlString = args[0]; } // Now we need to build an official URL object, create an HttpURLConnection object // to represent the connection to the appropriate server, and open the connection. URL url = new URL(urlString); HttpURLConnection urlCon = (HttpURLConnection) url.openConnection(); urlCon.connect(); // Opening the connection automatically constructed and sent a GET request. Now we // just need to read the response. First we ask the connection object for the // stream that will contain the incoming data, then we read data from the stream // until the data runs out. No need to deal with the HTTP header on the incoming // data -- HttpURLConnection is smart enough to strip that out for us. InputStream inputStream = urlCon.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = reader.readLine(); // reads a line while(line != null) { System.out.println(line); line = reader.readLine(); } } }