Tomcat源码学习(6)How Tomcat works(转)

Request

    ex01.pyrmont.Request类代表一个HTTP请求。从负责与客户端通信的Socket中传递过来InputStream对象来构造这个类的一个实例。你调用InputStream对象其中一个read方法来获取HTTP请求的原始数据。
    Request
类显示在Listing 1.3Request对象有parsegetUri两个公共方法,分别在Listings 1.41.5列出来。
         Listing 1.3: Request


package ex01.pyrmont;
import java.io.InputStream;
import java.io.IOException;
public class Request {
     private InputStream input;
     private String uri;
     public Request(InputStream input) {
         this.input = input;
     }
     public void parse() {
         ...
     }
     private String parseUri(String requestString) {
         ...
     }
     public String getUri() {
         return uri;
     }
}

         Listing 1.4: Request类的parse方法

public void parse() {
     // Read a set of characters from the socket
     StringBuffer request = new StringBuffer(2048);
     int i;
     byte[] buffer = new byte[2048];
     try {
         i = input.read(buffer);
     }
     catch (IOException e) {
         e.printStackTrace();
         i = -1;
     }
     for (int j=0; j<i; j++) {
         request.append((char) buffer[j]);
     }
     System.out.print(request.toString());
     uri = parseUri(request.toString());
}

         Listing 1.5: Request类的parseUri方法

private String parseUri(String requestString) {
     int index1, index2;
     index1 = requestString.indexOf(' ');
     if (index1 != -1) {
         index2 = requestString.indexOf(' ', index1 + 1);
         if (index2 > index1)
         return requestString.substring(index1 + 1, index2);
     }
     return null;
}

    parse方法解析HTTP请求里边的原始数据。这个方法没有做很多事情。它唯一可用的信息是通过调用HTTP请求的私有方法parseUri获得的URIparseUri方法在uri变量里边存储URI。公共方法getUri被调用并返回HTTP请求的URI
   
注意:在第3章和下面各章的附带程序里边,HTTP请求将会对原始数据进行更多的处理。
   
为了理解parseparseUri方法是怎样工作的,你需要知道上一节超文本传输协议(HTTP)”讨论的HTTP请求的结构。在这一章中,我们仅仅关注HTTP请求的第一部分,请求行。请求行从一个方法标记开始,接下去是请求的URI和协议版本,最后是用回车换行符(CRLF)结束。请求行里边的元素是通过一个空格来分隔的。例如,使用GET方法来请求index.html文件的请求行如下所示。

GET /index.html HTTP/1.1

    parse方法从传递给Requst对象的套接字的InputStream中读取整个字节流并在一个缓冲区中存储字节数组。然后它使用缓冲区字节数据的字节来填入一个StringBuffer对象,并且把代表StringBuffer的字符串传递给parseUri方法。
    parse
方法列在Listing 1.4
   
然后parseUri方法从请求行里边获得URIListing 1.5给出了parseUri方法。parseUri方法搜索请求里边的第一个和第二个空格并从中获取URI

原文地址:https://www.cnblogs.com/macula7/p/1960792.html