JDK6.0的新特性:轻量级Http Server
JDK6提供了一个简朴的Http Server API,据此我们可以构建本身的嵌入式Http Server,它支持Http和Https协议,提供了HTTP1.1的部门实现,没有被实现的那部门可以通过扩展已有的Http Server API来实现,措施员必需本身实现HttpHandler接口,HttpServer会挪用HttpHandler实现类的回调要领来处理惩罚客户端请求,在这里,我们把一个Http请求和它的响应称为一个互换,包装成HttpExchange类,HttpServer认真将HttpExchange传给HttpHandler实现类的回调要领.下面代码演示了奈何建设本身的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);//配置HttpServer的端口为8888
hs.createContext("/chinajash", new MyHandler());//用MyHandler类内处理惩罚到/chinajash的请求
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 = "<h3>Happy New Year 2007!–Chinajash</h3>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}