Wednesday, March 10, 2010

HTTPRequestHeader

/** HTTP Request Header
This Class represents a HTTP Request Header
It takes a byte array and Parses it, basically
Author: Daniel J. Tanner
Date:  March 9th, 2010
CMPT 352
*/
import java.io.*;
import java.net.*;
import java.lang.*;

public class HTTPRequestHeader
{
    //fields
    protected static final String DEFAULT_METHOD = "GET";
    protected static final String DEFAULT_PATH = "/index.html";
    protected static final String DEFAULT_PROTOCOL = "HTTP/1.0";
    protected static final int CHUNK = 5028;
    protected String method_;
    protected String path_;
    protected String protocol_;
   
    //Constructors
    public HTTPRequestHeader()
    {
        method_ = DEFAULT_METHOD;
        protocol_ = DEFAULT_PROTOCOL;
        path_ = DEFAULT_PATH;
    }
   
    //This one is basically the meat, it will parse the byte stream it receives
    public HTTPRequestHeader(InputStream fromClient)
    {
        BufferedReader input = new BufferedReader(new InputStreamReader(fromClient));
        String requestLine = null;
        String requestParsed = null;
        StringBuffer request = new StringBuffer(CHUNK);
        int i = 0;
        try
        {
            requestParsed = input.readLine();
       
            while((requestLine = input.readLine()) != null)
            {
                if(requestLine.length() == 0) break;
                i += requestLine.length();
                request.append(requestLine);
            }
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
            i = -1;
        }
       
        //Now we parse!
        //String requestParsed = request.toString();
        int index1, index2;
        i = requestParsed.length();
        index1 = requestParsed.indexOf(' ');
       
        //getMethod
        if(index1 != -1)
        {
            method_ = requestParsed.substring(0, index1 - 1);
        }
        index2 = requestParsed.indexOf(' ', index1 + 1);
       
        //getURI
        if(index2 > index1)
        {
            path_ = requestParsed.substring(index1 + 1, index2 - 1);
        }
        index1 = requestParsed.indexOf(' ', index2 + 1);
       
        //getProtocol
        if(index1 > index2)
        {
            protocol_ = requestParsed.substring(index2 + 1, index1 - 1);
        }
       
    }
   
    //Get Functions
    public String getMethod() {return method_;}
    public String getProtocol() {return protocol_;}
    public String getPath() {return path_;}
}

No comments:

Post a Comment