JDK6.0的新特性:輕量級(jí)Http Server
JDK6提供了一個(gè)簡(jiǎn)單的Http Server API,據(jù)此我們可以構(gòu)建自己的嵌入式Http Server,它支持Http和Https協(xié)議,提供了HTTP1.1的部分實(shí)現(xiàn),沒(méi)有被實(shí)現(xiàn)的那部分可以通過(guò)擴(kuò)展已有的Http Server API來(lái)實(shí)現(xiàn),程序員必須自己實(shí)現(xiàn)HttpHandler接口,HttpServer會(huì)調(diào)用HttpHandler實(shí)現(xiàn)類(lèi)的回調(diào)方法來(lái)處理客戶端請(qǐng)求,在這里,我們把一個(gè)Http請(qǐng)求和它的響應(yīng)稱為一個(gè)交換,包裝成HttpExchange類(lèi),HttpServer負(fù)責(zé)將HttpExchange傳給HttpHandler實(shí)現(xiàn)類(lèi)的回調(diào)方法.下面代碼演示了怎樣創(chuàng)建自己的Http Server
/**
* Created by IntelliJ IDEA.
* User: Chinajash
* Date: Dec 30, 2006
*/
public class HTTPServerAPITester {
public static void main(String[] args) {
try {
HttpServer hs = HttpServer.create(new InetSocketAddress(8888),0);//設(shè)置HttpServer的端口為8888
hs.createContext("/chinajash", new MyHandler());//用MyHandler類(lèi)內(nèi)處理到/chinajash的請(qǐng)求
hs.setExecutor(null); // creates a default executor
hs.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
String response = "
Happy New Year 2007!--Chinajash
";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}