我以如下方式結束了重構。我創建了一個類HttpPatterns
:
package cs236369.proxy.types;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public enum HttpPatterns {
RESPONSE_CODE("^HTTP/1\\.1 (\\d+) .*$"),
CACHE_CONTROL("^Cache-Control: (\\w+)$"),
HOST("^Host: (\\w+)$"),
REQUEST_HEADER("(GET|POST) ([^\\s]+) ([^\\s]+)$"),
ACCEPT_ENCODING("^Accept-Encoding: .*$"),
CONTENT_ENCODING("^Content-Encoding: ([^\\s]+)$");
private final Pattern pattern;
HttpPatterns(String regex) {
pattern = Pattern.compile(regex);
}
public boolean matches(String expression) {
return pattern.matcher(expression).matches();
}
public Object process(String expression) {
Matcher matcher = pattern.matcher(expression);
if (!matcher.matches()) {
throw new RuntimeException("Called `process`, but the expression doesn't match. Call `matches` first.");
}
if (this == RESPONSE_CODE) {
return Integer.parseInt(matcher.group(1));
} else if (this == CACHE_CONTROL) {
return CacheControl.parseString(matcher.group(1));
} else if (this == HOST) {
return matcher.group(1);
} else if (this == REQUEST_HEADER) {
return new RequestHeader(RequestType.parseString(matcher.group(1)), matcher.group(2), matcher.group(3));
} else if (this == CONTENT_ENCODING) {
return ContentEncoding.parseString(matcher.group(1));
} else { //never happens
return null;
}
}
}
我用它像這樣:
String line;
while ((line = reader.readLine()) != null) {
if (HttpPatterns.CACHE_CONTROL.matches(line)) {
cacheControl = (CacheControl) HttpPatterns.RESPONSE_CODE.process(line);
} else if (HttpPatterns.REQUEST_HEADER.matches(line)) {
requestHeader = (RequestHeader) HttpPatterns.REQUEST_HEADER.process(line);
} else if (HttpPatterns.HOST.matches(line)) {
requestHost = (String) HttpPatterns.HOST.process(line);
} else if (HttpPatterns.ACCEPT_ENCODING.matches(line)) {
continue;
} else if (line.isEmpty()) {
break;
}
fullRequest += "\r\n" + line;
}
我不喜歡,我要投的一切,我得到的,但是這是我迄今爲止所發現的最佳解決方案。
僅供參考,'while(reader.ready())'不正確。 'ready()'方法告訴你Reader是否可以在不阻塞的情況下讀取更多*,而不是如果有更多的文本被讀取。一行一行的閱讀習慣是'while((line = reader.readLine())!= null)'。 – 2011-04-15 15:02:51