JDK6提供了一个简单的Http Server API,据此我们可以构建自己的嵌入式Http Server,它支持Http和Https协议,提供了HTTP1.1的部分实现,没有被实现的那部分可以通过扩展已有的Http Server API来实现,程序员必须自己实现HttpHandler接口,HttpServer会调用HttpHandler实现类的回调方法来处理客户端请求,在这里,我们把一个Http请求和它的响应称为一个交换,包装成HttpExchange类,HttpServer负责将HttpExchange传给HttpHandler实现类的回调方法。下面代码演示了怎样创建自己的Http Server。
在浏览器中输入地址http://localhost:7777/myrequest?a=1,就可以看到结果。
package com.ajita;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.*;
public class MyHttpServer {
public static void main(String[] args) {
try {
HttpServer hs = HttpServer.create(new InetSocketAddress(7777), 0);
hs.createContext("/myrequest", new MyHandler());
hs.setExecutor(null);
hs.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
System.out.println(t.getRequestURI().toString());
InputStream is = t.getRequestBody();
byte[] temp = new byte[is.available()];
is.read(temp);
System.out.println(new String(temp));
String response = "<h3>Hello World!</h3>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
在浏览器中输入地址http://localhost:7777/myrequest?a=1,就可以看到结果。