import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.net.Socket; /** Use a socket to communicate with a web server. Source: Big Java p. 861 */ public class WebGet { public static void main(String[] args) throws IOException { //get command lnie arguments if (args.length != 2) { System.out.println("usage: java WebGet host resource"); System.exit(0); } String host = args[0]; String resource = args[1]; // open socket final int HTTP_PORT = 80; Socket s = new Socket(host, HTTP_PORT); // get streams InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); // turn streams into readers and writers BufferedReader reader = new BufferedReader(new InputStreamReader(in)); PrintWriter writer = new PrintWriter(out); // send command String command = "GET /" + resource + " HTTP/1.0\n\n"; writer.print(command); writer.flush(); // read server response String input; while ((input = reader.readLine()) != null) System.out.println(input); // close socket s.close(); } }