博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JDK6.0的新特性:轻量级Http Server
阅读量:4030 次
发布时间:2019-05-24

本文共 1156 字,大约阅读时间需要 3 分钟。

转载:http://java.chinaitlab.com/JDK/713255.html
 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();
 }
}
你可能感兴趣的文章
iphone开发基础之objective-c学习
查看>>
iphone开发之SDK研究(待续)
查看>>
计算机网络复习要点
查看>>
Variable property attributes or Modifiers in iOS
查看>>
NSNotificationCenter 用法总结
查看>>
C primer plus 基础总结(一)
查看>>
剑指offer算法题分析与整理(一)
查看>>
剑指offer算法题分析与整理(三)
查看>>
部分笔试算法题整理
查看>>
Ubuntu 13.10使用fcitx输入法
查看>>
pidgin-lwqq 安装
查看>>
mint/ubuntu安装搜狗输入法
查看>>
C++动态申请数组和参数传递问题
查看>>
opencv学习——在MFC中读取和显示图像
查看>>
retext出现Could not parse file contents, check if you have the necessary module installed解决方案
查看>>
pyQt不同窗体间的值传递(一)——对话框关闭时返回值给主窗口
查看>>
linux mint下使用外部SMTP(如网易yeah.net)发邮件
查看>>
北京联通华为光猫HG8346R破解改桥接
查看>>
python使用win32*模块模拟人工操作——城通网盘下载器(一)
查看>>
python append 与浅拷贝
查看>>