love fish大鵬一曰同風起,扶搖直上九萬里

          常用鏈接

          統計

          積分與排名

          friends

          link

          最新評論

          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-11 15:29 liaojiyong 閱讀(246) 評論(0)  編輯  收藏 所屬分類: Java

          主站蜘蛛池模板: 乐昌市| 阿尔山市| 昌吉市| 四子王旗| 伊宁市| 牙克石市| 虞城县| 哈巴河县| 育儿| 任丘市| 云梦县| 上饶县| 津市市| 色达县| 萨嘎县| 马尔康县| 延川县| 濮阳县| 博爱县| 开封县| 博野县| 昭苏县| 东安县| 上饶县| 迁西县| 饶平县| 偏关县| 当阳市| 汤原县| 盐源县| 静海县| 襄城县| 清涧县| 抚顺县| 永寿县| 宁强县| 精河县| 洛川县| 东乡族自治县| 巴东县| 鄂州市|