冷面阎罗

低调做人&&高调做事
随笔 - 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 冷面阎罗 阅读(3297) 评论(1)  编辑  收藏 所属分类: java

评论

# re: JDK6.0的新特性:轻量级Http Server  回复  更多评论   

能决输出中文内容的问题吗!!!

···············
2007-08-23 17:04 | shish

只有注册用户登录后才能发表评论。


网站导航: