package webexample; import java.io.*; import java.net.*; /** * A very simple web reading example that won't work in some circumstances. * But it will in some others. * * @author mcgredo */ public class WebExample { /** * @param args the command line arguments */ public static void main(String[] args) { try { System.out.println("creating web connection"); // We request an IP to connect to a web server running // on port 80. Socket socket = new Socket("movesinstitute.org", 80); // we send a command to the web server, asking for what // we want. Note that the format for the command is very // specific and documented. OutputStream os = socket.getOutputStream(); PrintStream ps = new PrintStream(os); ps.print("GET /index.html HTTP/1.0"); // Commands have to terminate with "carriage return/line feed" // twice to end the request. Those are the special characters // to have the control characters printed. ps.print("\r\n\r\n"); ps.flush(); // Up until now we have been reading one line only. But // a web server will write an unknown number of lines. We // read until the transmisson ends. InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; int count = 0; while((line = br.readLine()) != null) { count++; System.out.println(count + ": " + line); } System.out.println("web server message finished"); } catch(Exception e) { System.out.println(e); System.out.println("Problem with client"); } } }