知识库--parsing headers

来源:互联网 发布:金数据官网 编辑:程序博客网 时间:2024/06/07 01:40

Parsing Headers

An Http headers is represented by the HttpHeader class. This class will be explained in detail in 4, for now it is sufficient to know the following:
You can construct an HttpHeader instance by using its class’s no-argument constructor.
Once you have an HttpHeader instance , you can pass it to the readHeader method of SocketInputStream. If there is a header to read, the readHeader method will populate the HttpHeader object accordingly. If there is no more header to read, both nameEnd and valueEnd fields of the HttpHeader instance will be zero.
To obtain the header name and value, using the following:
String name = new String(header.name, 0 ,header.nameEnd);
String value = new String(header.value, 0, header.valueEnd);
The parseHeaders method contains a while loop that keeps reading headers from the SocketInputStream until there is no more header.The loop starts by constructing an HttpHeader instance and passing it to the SocketInputSteam class’s readHeader:

HttpHeader header = new HttpHeader();//read  the next headerinput.readHeader(header);

Then ,you cans test whether or not there is a next header to be read from the input stream by testing the nameEnd and valueEnd fields of the HttpHeader instace:

if(header.nameEnd ==0){    if(header.valueEnd == 0){       return;     }     else{       throw new  ServletException(sm.getString("httpProcessor.parseHeander.colon"))       } }

If there is a next header, the header name and value can than be retrieved:

    String name = new String(header.name,0,header.nameEnd);    String value = new String(header.value,0,header.valueEnd);

Once you get the header name and value, you add it to the headers HashMap in the HttpRequest object by calling its addHeader method:

reqest.addHeader(name,value);

Some headers also required the setting of some properties. For instance, the value of the content-length header is to be returned when the servlet calls the getContentLength method of javax.servlet.ServletRequest, and the cookie header contains cookies to be added to the cookie collection. Thus, here is some processing:

    if(name.equals("cookie")){        ..//process cookies here    }    else if(name.equals("content-length")){        int n = -1;        try{            n = Integer.parseInt(value);        }catch(Exception e){            throw new ServletException(sm.getString("httpProcessor.parseHeaders.contentLength"));        }        request.setContentLenth(n);    }    else if(name.equals("content-type")){        request.setContentType(value);    }

Cookie parsing is dicussed in the next section, Parsing Cookies.

0 0
原创粉丝点击