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)類的回調(diào)方法來(lái)處理客戶端請(qǐng)求,在這里,我們把一個(gè)Http請(qǐng)求和它的響應(yīng)稱為一個(gè)交換,包裝成HttpExchange類,HttpServer負(fù)責(zé)將HttpExchange傳給HttpHandler實(shí)現(xiàn)類的回調(diào)方法.下面代碼演示了怎樣創(chuàng)建自己的Http Server
package?jdk6;

import?java.io.IOException;
import?java.net.InetSocketAddress;


import?com.sun.net.httpserver.HttpServer;


public?class?HTTPServerAPITester?
{
????

????/**?*//**
?????*?The?main?method.
?????*?
?????*?@param?args?the?args
?????*/

????public?static?void?main(String[]?args)?
{

????????try?
{
????????????HttpServer?hs?=?HttpServer.create(new?InetSocketAddress(8888),0);//設(shè)置HttpServer的端口為8888
????????????hs.createContext("/soddabao",?new?MyHandler());//用MyHandler類內(nèi)處理到/chinajash的請(qǐng)求
????????????hs.setExecutor(null);?//?creates?a?default?executor
????????????hs.start();

????????}?catch?(IOException?e)?
{
????????????e.printStackTrace();
????????}
????}
}
package?jdk6;

import?java.io.IOException;
import?java.io.OutputStream;

import?com.sun.net.httpserver.HttpExchange;
import?com.sun.net.httpserver.HttpHandler;

//?TODO:?Auto-generated?Javadoc

/**?*//**
?*?The?Class?MyHandler.
?*/

public?class?MyHandler?implements?HttpHandler?
{
???????

???????/**//*?(non-Javadoc)
????????*?@see?com.sun.net.httpserver.HttpHandler#handle(com.sun.net.httpserver.HttpExchange)
????????*/

???????public?void?handle(HttpExchange?httpexchnge)?throws?IOException?
{
??????????????httpexchnge.getRequestBody();
???????????String?response?=?"<h3>Happy?New?Year?2007!--Soddabao</h3>";
???????????httpexchnge.sendResponseHeaders(200,?response.length());
???????????OutputStream?os?=?httpexchnge.getResponseBody();
???????????os.write(response.getBytes());
???????????os.close();
???????}
????}