import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;

public class HttpGet{
	private final static int HOST_INDEX  = 0;
	private final static int PATH_INDEX  = 1;
	private final static int WWW_PORT    = 80;
	private final static String HTTP_VER = "HTTP/1.0";



	private int handleException(Exception e){
		if(e instanceof SecurityException){
			System.out.println("SecurityException: Operation not allowed");
		}

		if(e instanceof IOException){
			System.out.println("IOException: I/O error");
		}

		if(e instanceof UnknownHostException){
			System.out.println("UnknownHostException: IP address of the host could not be determined");
		}

		System.out.println("Returning -1");
		return -1;
	}



	private void sendGetRequest(String filename, BufferedWriter out) throws IOException{
		String getRequest = "GET " + filename + " " + HTTP_VER + "\r\n\r\n";

		out.write(getRequest);
		out.flush();
	}



	private void receiveGetResponse(BufferedReader in) throws IOException{
		String line;

    	while ((line = in.readLine()) != null) {
     		System.out.println(line);
		}				
	}



	public int start(String[] argv){
		try{
			Socket socket = new Socket(argv[HOST_INDEX], WWW_PORT);

			BufferedReader in = 
				new BufferedReader(new InputStreamReader(socket.getInputStream()));

			BufferedWriter out = 
				new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 

			sendGetRequest(argv[PATH_INDEX], out);
			receiveGetResponse(in);

			in.close();
			out.close();
		}

		catch(Exception e){
			return handleException(e);
		}

		return 0;
	}



	public static void main(String[] argv){
		HttpGet get = new HttpGet();
		System.exit(get.start(argv));
	}
}
