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倍