/** * This program connects to a web server and gets header infor from it. * Xiannong Meng * 03-07-2011 * xmeng@bucknell.edu */ import java.io.*; import java.net.*; import java.util.*; class HttpHeader { public static int PORT = 80; // default web port public static void main(String[] args) throws IOException { if (args.length != 1 && args.length != 2 && args.length != 3) { System.out.println(" usage: host [dir port]"); System.exit(1); } if (args.length == 3) { // a port number is supplied PORT = Integer.parseInt(args[2]); } Socket t = new Socket(args[0], PORT); // create a socket String cmd; if (args.length == 1) // get the root page cmd = new String("HEAD / HTTP/1.0\n"); else { // get a specific page cmd = new String("HEAD /"); cmd += args[1].trim(); cmd += " HTTP/1.0\n"; } cmd += "Host: " + args[0].trim() + "\n"; cmd += "Connection: Keep-Alive\n"; cmd += "UserAgent: self-module\n"; cmd += "Accept: image/gif, image/x-xbitmap, image/jpeg, text/html\n"; cmd += "\r\n\r\n"; System.out.println("sending command :"); System.out.println(cmd); // connecting to socket input and output BufferedReader is = new BufferedReader (new InputStreamReader (new DataInputStream(t.getInputStream()))); PrintStream out = new PrintStream(t.getOutputStream()); out.print(cmd); out.flush(); int count = 0; String inBuffer = new String(); boolean more = true; inBuffer = readHttpHeader(is); System.out.println("header : " + inBuffer); } // main public static String readHttpHeader(BufferedReader fileIn) { String inBuffer = ""; try { String line; do { line = fileIn.readLine(); inBuffer += line + "\r\n"; if (line.length() == 2 && line.compareTo("\n\n") == 0) { System.out.println("we hit the break in readAll"); break; } } while (line.length() > 0); } catch (IOException ignored) {}; return inBuffer; } }