/*
* 设定用于解析HTTP请求的字符串匹配模式。对于以下形式的HTTP请求:
*
* GET /dir/file HTTP/1.1
* Host: hostname
*
* 将被解析成:
*
* group[1] = "GET"
* group[2] = "/dir/file"
* group[3] = "1.1"
* group[4] = "hostname"
*/
private static Pattern requestPattern
= Pattern.compile("\\A([A-Z]+) +([^ ]+) +HTTP/([0-9\\.]+)$"
+ ".*^Host: ([^ ]+)$.*\r\n\r\n\\z",
Pattern.MULTILINE | Pattern.DOTALL);
/* 解析HTTP请求,创建相应的Request对象 */
public static Request parse(ByteBuffer bb) throws MalformedRequestException {
bb=deleteContent(bb); //删除请求正文
CharBuffer cb = requestCharset.decode(bb); //解码
Matcher m = requestPattern.matcher(cb); //进行字符串匹配
//如果HTTP请求与指定的字符串模式不匹配,说明请求数据不正确
if (!m.matches())
throw new MalformedRequestException();
Action a;
try { //获得请求方式
a = Action.parse(m.group(1));
} catch (IllegalArgumentException x) {
throw new MalformedRequestException();
}
URI u;
try { //获得URI
u = new URI("http://"
+ m.group(4)
+ m.group(2));
} catch (URISyntaxException x) {
throw new MalformedRequestException();
}
//创建一个Request对象,并将其返回
return new Request(a, m.group(3), u);
}
}
7.代表HTTP响应的Response类
Response类表示HTTP响应。它有三个成员变量:code、headerBuffer和content,它们分别表示HTTP响应中的状态代码、响应头和正文。Response类的prepare()方法负责准备HTTP响应的响应头和正文内容,send()方法负责发送HTTP响应的所有数据。例程7是Response类的源程序:
//例程7 Response.java
//此处省略import语句
public class Response implements Sendable {
static class Code { //枚举类,表示状态代码
private int number;
private String reason;
private Code(int i, String r) { number = i; reason = r; }
public String toString() { return number + " " + reason; }
static Code OK = new Code(200, "OK");
static Code BAD_REQUEST = new Code(400, "Bad Request");
static Code NOT_FOUND = new Code(404, "Not Found");
static Code METHOD_NOT_ALLOWED = new Code(405, "Method Not Allowed");
}
|