001package edu.pdx.cs410J.web; 002 003import java.net.Socket; 004import java.io.*; 005 006/** 007 * Sends an HTTP request to a server via a socket. This demonstrates HTTP at a very low level. 008 * 009 * @author David Whitlock 010 * @since Summer 2008 011 */ 012public class RawHttpGet { 013 014 /** 015 * Contacts the HTTP server on the given host and port and GETs the given file 016 * 017 * @param host The name/address of the host machine 018 * @param port The HTTP port 019 * @param file The file to GET 020 * @throws java.io.IOException If we can't communicate with the server 021 */ 022 private static void getHttp(String host, int port, String file) throws IOException { 023 Socket socket = new Socket(host, port); 024 Writer output = new OutputStreamWriter(socket.getOutputStream()); 025 InputStreamReader input = new InputStreamReader(socket.getInputStream()); 026 027 output.write("GET "); 028 output.write(file); 029 output.write(" HTTP/1.1"); 030 output.write("\r\n"); 031 output.write("Host: "); 032 output.write(host); 033 output.write("\r\n"); 034 output.write("\r\n"); 035 output.flush(); 036 037 BufferedReader br = new BufferedReader(input); 038 do { 039 System.out.println(br.readLine()); 040 } while (br.ready()); 041 042 br.close(); 043 output.close(); 044 } 045 046 public static void main(String[] args) throws IOException { 047 String host = null; 048 String file = null; 049 int port = 80; 050 051 for (String arg : args) { 052 if (arg.equals("-port")) { 053 port = Integer.parseInt(arg); 054 055 } else if (host == null) { 056 host = arg; 057 058 } else if (file == null) { 059 file = arg; 060 061 } else { 062 usage("Extraneous command line argument: " + arg); 063 } 064 } 065 066 if (host == null) { 067 usage("Missing host"); 068 069 } else if (file == null) { 070 usage("Missing file"); 071 } 072 073 getHttp(host, port, file); 074 } 075 076 private static void usage(String message) { 077 PrintStream err = System.err; 078 err.println("** " + message); 079 err.println("usage: java RawHttpGet [-port port] host file"); 080 System.exit(1); 081 } 082}