import
java.io.IOException;
import
java.io.InputStream;
import
java.io.OutputStream;
import
java.io.OutputStreamWriter;
import
java.io.PrintWriter;
import
java.net.InetSocketAddress;
import
java.util.List;
import
java.util.Map;
import
com.sun.net.httpserver.Headers;
import
com.sun.net.httpserver.HttpContext;
import
com.sun.net.httpserver.HttpExchange;
import
com.sun.net.httpserver.HttpHandler;
import
com.sun.net.httpserver.HttpServer;
public
class
HttpServerAPITest2 {
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
"
,
"
HTML/plain;charset=utf-8
"
);
printWriter.println(
"
<font color='red'>--------------------------</font>
"
);
Headers requestHeaders
=
he.getRequestHeaders();
for
(Map.Entry
<
String, List
<
String
>>
entry : requestHeaders.entrySet()) {
printWriter.println(
"
</br>
"
+
entry.getKey()
+
"
:
"
+
entry.getValue());
}
printWriter.println(
"
</br>
"
+
"
<font color='red'>--------------------------</font>
"
);
Headers responseHeaders
=
he.getResponseHeaders();
for
(Map.Entry
<
String, List
<
String
>>
entry : responseHeaders.entrySet())
printWriter.println(
"
</br>
"
+
entry.getKey()
+
"
:
"
+
entry.getValue());
printWriter.println(
"
</br>
"
+
"
<font color='red'>--------------------------</font>
"
);
printWriter.println(
"
</br>
"
+
he.getHttpContext().getPath());
printWriter.println(
"
</br>
"
+
"
<font color='red'>--------------------------</font>
"
);
printWriter.println(
"
</br>
"
+
he.getLocalAddress().getHostName());
printWriter.println(
"
</br>
"
+
he.getLocalAddress().getAddress());
printWriter.println(
"
</br>
"
+
he.getLocalAddress().getPort());
printWriter.println(
"
<font color='red'>--------------------------</font>
"
);
printWriter.close();
}
}
}
访问:
http://127.0.0.1:8888/--------------------------Host: [127.0.0.1:8888]
Accept-encoding: [gzip, deflate]
Connection: [Keep-Alive]
Accept-language: [zh-cn,en-US;q=0.5]
Ua-cpu: [x86]
User-agent: [Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; MAXTHON 2.0)]
Accept: [*/*]
--------------------------Transfer-encoding: [chunked]
Content-type: [HTML/plain;charset=utf-8]
--------------------------/
--------------------------localhost
localhost/127.0.0.1
8888
--------------------------
posted on 2007-06-22 14:13
交口称赞 阅读(2194)
评论(0) 编辑 收藏 所属分类:
Java6