创建HttpRequest对象
HttpRequest类实现了javax.servlet.http.HttpServletRequest。跟随它的是一个叫做 HttpRequestFacade的facade类。
解析HTTP请求是一个相当复杂的事情,主要有以下几个部分:
- 读取套接字的输入流
- 解析请求行
- 解析头部
- 解析cookies
- 获取参数
- 列表内容
- 列表内容
1,读取套接字的输入流
byte[] buffer = new byte [2048];
try {
// input is the InputStream from the socket.
i = input.read(buffer);
}
一般地,我们通过java.io.InputStream类的read方法来获取请求行,包括方法、URI和HTTP版本。
在本章例子中,你可以通过ex03.pyrmont.connector.http.SocketInputStream类来获取更多的请求信息,不仅可以获取请求行,还可以获取请求的头部。你通过传递一个InputStream和一个指代实例使用的缓冲区大小的整数,来构建一个SocketInputStream实例,如下:
input = new SocketInputStream(socket.getInputStream(), 2048);
通过上一篇博客可以知道,SocketInputStream类主要作用是提供了readRequestLine和readHeader这两个方法,这两个方法在前面已经分析过了。
2,解析请求行
GET /servlet/ModernServlet?userName=tarzan&password=pwd HTTP/1.1
这是一个HTTP请求行的例子,HttpProcessor的process方法调用私有方法parseRequest用来解析请求行。第一部分是请求的方法,第二部分是URL再加上一个查询字符串,在上面例子中uri应该是:
/servlet/ModernServlet
查询字符串是:
userName=tarzan&password=pwd
查询字符串一般是键值对的形式,可以包含0个或多个参数。在servlet/JSP编程中,参数名jsessionid是用来携带一个会话标识符。会话标识符经常被作为cookie来嵌入,但是程序员可以选择把它嵌入到查询字符串去,例如,当浏览器的cookie被禁用的时候。
当parseRequest方法被调用时,request变量指向了一个HttpRequest实例,。parseRequest方法解析请求行用来获得几个值并把这些值赋给HttpRequest对象。
parseRequest已经在前介绍过,这里再补充一些细节。
readRequestLine方法来告诉SocketInputStream去填入HttpRequestLine实例,在接下去,parseRequest方法获得请求行的方法,URI和协议:
String method = new String(requestLine.method, 0,
requestLine.methodEnd);
String uri = null;
String protocol = new String(requestLine.protocol, 0,
requestLine.protocolEnd);
不过HttpRequestLine中uri可能还包含查询字符串,如果存在的话,查询字符串会以一个?和uri分割开。因此,parseRequest方法试图首先获取查询字符串。并调用setQueryString方法来填充HttpRequest对象:
// Parse any query parameters out of the request URI
int question = requestLine.indexOf("?");
if (question >= 0) {
request.setQueryString(new String(requestLine.uri, question + 1,
requestLine.uriEnd - question - 1));
uri = new String(requestLine.uri, 0, question);
} else {
request.setQueryString(null);
uri = new String(requestLine.uri, 0, requestLine.uriEnd);
}
如果存在查询字符串,分离出它,并把它和uri同时set到request对象中。
3,解析头部
一个HTTP头部是用类HttpHeader来代表的:
- 你可以通过使用类的无参数构造方法构造一个HttpHeader实例。
- 一旦你拥有一个HttpHeader实例,你可以把它传递给SocketInputStream的readHeader方法。假如这里有头部需要读取,readHeader方法将会相应的填充HttpHeader对象。假如再也没有头部需要读取了,HttpHeader实例的nameEnd和valueEnd字段将会置零。
- 为了获取头部的名称和值,使用下面的方法:
- String name = new String(header.name, 0, header.nameEnd);
- String value = new String(header.value, 0, header.valueEnd);
4,解析cookies
// do something for some headers, ignore others.
if (name.equals("cookie")) {
Cookie cookies[] = RequestUtil.parseCookieHeader(value);
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("jsessionid")) {
// Override anything requested in the URL
if (!request.isRequestedSessionIdFromCookie()) {
// Accept only the first session id cookie
request.setRequestedSessionId(
cookies[i].getValue());
request.setRequestedSessionCookie(true);
request.setRequestedSessionURL(false);
}
}
request.addCookie(cookies[i]);
}
}
5,获取参数
你不需要马上解析查询字符串或者HTTP请求内容,直到servlet需要通过调用javax.servlet.http.HttpServletRequest的getParameter,getParameterMap, getParameterNames或者getParameterValues方法来读取参数。因此,HttpRequest的这四个方法开头调用了parseParameter方法。
参数可以在查询字符串或是请求内容里找到。假如用户使用GET方法来请求servlet的话,所有的参数将在查询字符串里边出现。假如使用POST方法的话,你也可以在请求内容中找到一些。
protected void parseParameters() {
if (parsed)
return;
ParameterMap results = parameters;
if (results == null)
results = new ParameterMap();
results.setLocked(false);
String encoding = getCharacterEncoding();
if (encoding == null)
encoding = "ISO-8859-1";
// Parse any parameters specified in the query string
String queryString = getQueryString();
try {
RequestUtil.parseParameters(results, queryString, encoding);
} catch (UnsupportedEncodingException e) {
;
}
// Parse any parameters specified in the input stream
String contentType = getContentType();
if (contentType == null)
contentType = "";
int semicolon = contentType.indexOf(';');
if (semicolon >= 0) {
contentType = contentType.substring(0, semicolon).trim();
} else {
contentType = contentType.trim();
}
if ("POST".equals(getMethod()) && (getContentLength() > 0)
&& "application/x-www-form-urlencoded".equals(contentType)) {
try {
int max = getContentLength();
int len = 0;
byte buf[] = new byte[getContentLength()];
ServletInputStream is = getInputStream();
while (len < max) {
int next = is.read(buf, len, max - len);
if (next < 0) {
break;
}
len += next;
}
is.close();
if (len < max) {
throw new RuntimeException("Content length mismatch");
}
RequestUtil.parseParameters(results, buf, encoding);
} catch (UnsupportedEncodingException ue) {
;
} catch (IOException e) {
throw new RuntimeException("Content read fail");
}
}
// Store the final results
results.setLocked(true);
parsed = true;
parameters = results;
}