import
java.io.IOException;
import
java.io.OutputStream;
import
java.io.OutputStreamWriter;
import
java.io.PrintWriter;
import
java.net.InetSocketAddress;
import
com.sun.net.httpserver.HttpExchange;
import
com.sun.net.httpserver.HttpHandler;
import
com.sun.net.httpserver.HttpServer;
public
class
HttpServerTestHello {
public
static
void
main(String[] args) {
try
{
HttpServer hs
=
HttpServer.create(
new
InetSocketAddress(
8888
),
0
);
hs.createContext(
"
/
"
,
new
MyHandler());
hs.start();
System.out.println(
"
---Start---
"
);
System.out.println(hs.getAddress().getHostName());
System.out.println(hs.getAddress().getPort());
System.out.println(hs.getAddress().getAddress());
}
catch
(IOException ioe) {
ioe.printStackTrace();
}
}
static
class
MyHandler
implements
HttpHandler {
public
void
handle(HttpExchange he)
throws
IOException {
he.sendResponseHeaders(
200
,
0
);
OutputStream os
=
he.getResponseBody();
PrintWriter printWriter
=
new
PrintWriter(
new
OutputStreamWriter(os,
"
UTF-8
"
));
he.getResponseHeaders().set(
"
Content-Type
"
,
"
text/plain;charset=UTF-8
"
);
printWriter.println(
"
hello hermit
"
);
printWriter.close();
}
}
}
访问:
http://127.0.0.1:8888/hello hermit
posted on 2007-06-22 14:11
交口称赞 阅读(1432)
评论(2) 编辑 收藏 所属分类:
Java6