?? request.java
字號:
import java.net.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.regex.*;
/* 代表客戶的HTTP請求 */
public class Request {
static class Action { //枚舉類,表示HTTP請求方式
private String name;
private Action(String name) { this.name = name; }
public String toString() { return name; }
static Action GET = new Action("GET");
static Action PUT = new Action("PUT");
static Action POST = new Action("POST");
static Action HEAD = new Action("HEAD");
public static Action parse(String s) {
if (s.equals("GET"))
return GET;
if (s.equals("PUT"))
return PUT;
if (s.equals("POST"))
return POST;
if (s.equals("HEAD"))
return HEAD;
throw new IllegalArgumentException(s);
}
}
private Action action;
private String version;
private URI uri;
public Action action() { return action; }
public String version() { return version; }
public URI uri() { return uri; }
private Request(Action a, String v, URI u) {
action = a;
version = v;
uri = u;
}
public String toString() {
return (action + " " + version + " " + uri);
}
private static Charset requestCharset = Charset.forName("GBK");
/* 判斷ByteBuffer是否包含了HTTP請求的所有數據。
* HTTP請求以“\r\n\r\n”結尾。
*/
public static boolean isComplete(ByteBuffer bb) {
ByteBuffer temp=bb.asReadOnlyBuffer();
temp.flip();
String data=requestCharset.decode(temp).toString();
if(data.indexOf("\r\n\r\n")!=-1){
return true;
}
return false;
}
/*
* 刪除請求正文,本例子僅支持GET和HEAD請求方式,忽略HTTP請求中的正文部分
*/
private static ByteBuffer deleteContent(ByteBuffer bb) {
ByteBuffer temp=bb.asReadOnlyBuffer();
String data=requestCharset.decode(temp).toString();
if(data.indexOf("\r\n\r\n")!=-1){
data=data.substring(0,data.indexOf("\r\n\r\n")+4);
return requestCharset.encode(data);
}
return bb;
}
/*
* 設定用于解析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);
}
}
/****************************************************
* 作者:孫衛琴 *
* 來源:<<Java網絡編程精解>> *
* 技術支持網址:www.javathinker.org *
***************************************************/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -