冷面閻羅

          低調做人&&高調做事
          隨筆 - 208, 文章 - 3, 評論 - 593, 引用 - 0
          數據加載中……

          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
          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);//設置HttpServer的端口為8888
          ????????????hs.createContext("/soddabao",?new?MyHandler());//用MyHandler類內處理到/chinajash的請求
          ????????????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();
          ???????}

          ????}

          posted on 2007-01-10 19:59 冷面閻羅 閱讀(3310) 評論(1)  編輯  收藏 所屬分類: java

          評論

          # re: JDK6.0的新特性:輕量級Http Server  回復  更多評論   

          能決輸出中文內容的問題嗎!!!

          ···············
          2007-08-23 17:04 | shish
          主站蜘蛛池模板: 平塘县| 怀来县| 平邑县| 博客| 萨迦县| 青铜峡市| 安宁市| 宁海县| 合川市| 巴彦淖尔市| 房山区| 焦作市| 新化县| 永德县| 和田县| 罗城| 香河县| 尚义县| 城步| 怀安县| 库尔勒市| 甘孜县| 闽侯县| 手机| 改则县| 毕节市| 龙门县| 遂昌县| 堆龙德庆县| 五华县| 临城县| 临沭县| 利辛县| 会东县| 和平区| 齐齐哈尔市| 湘乡市| 巴楚县| 清流县| 平原县| 梁河县|