639
技術社區[雲棲]
JDK6.0的新特性:輕量級HttpServer
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(); } } |
最後更新:2017-04-02 06:52:12
上一篇:
天氣預報抓取、解析(傳遞抓取的info參數)功能模塊實現(代碼)
下一篇:
自定義 mrtg 數據
egg-tablestore
雲服務器 ECS > > 快速入門(一)
數組、指針與引用類型
jQuery對select的基本操作
Changing the Way of Continuous Delivery with Docker (Part 1)
WIKIOI-1277 生活大爆炸
[原創]利用MASM宏顯示環境變量
android集成支付寶簡介
ICADL2012- A Scalable, Adaptive, Self-management and Fault-tolerant Architecture for Digital Library
中國擁有全球最快超級計算機 速度超美國1倍