1 |
torben |
1947 |
package dk.thoerup.test;
|
2 |
|
|
|
3 |
|
|
import java.io.IOException;
|
4 |
|
|
import java.net.HttpURLConnection;
|
5 |
|
|
import java.net.InetSocketAddress;
|
6 |
|
|
|
7 |
|
|
import com.sun.net.httpserver.HttpExchange;
|
8 |
|
|
import com.sun.net.httpserver.HttpHandler;
|
9 |
|
|
import com.sun.net.httpserver.HttpServer;
|
10 |
|
|
|
11 |
|
|
public class WebserverTest {
|
12 |
|
|
|
13 |
|
|
public static class TestListener implements HttpHandler {
|
14 |
|
|
|
15 |
|
|
@Override
|
16 |
|
|
public void handle(HttpExchange http) throws IOException {
|
17 |
|
|
StringBuffer sb = new StringBuffer();
|
18 |
|
|
|
19 |
|
|
sb.append("Local: ").append( http.getLocalAddress().toString() ).append("\n");
|
20 |
|
|
sb.append("Remote: ").append( http.getRemoteAddress().toString() ).append("\n");
|
21 |
|
|
sb.append("Context path: ").append( http.getHttpContext().getPath() ) .append("\n");
|
22 |
|
|
|
23 |
|
|
sb.append("Protocol: ").append( http.getProtocol() ).append("\n");
|
24 |
|
|
sb.append("Method: ").append(http.getRequestMethod() ).append("\n");
|
25 |
|
|
sb.append("URI: ").append( http.getRequestURI().toString() ).append("\n");
|
26 |
|
|
|
27 |
|
|
|
28 |
|
|
byte bytes[] = sb.toString().getBytes();
|
29 |
|
|
|
30 |
|
|
http.getResponseHeaders().add("Content-Type", "text/plain");
|
31 |
|
|
http.sendResponseHeaders(HttpURLConnection.HTTP_OK, bytes.length );
|
32 |
|
|
http.getResponseBody().write(bytes);
|
33 |
|
|
http.close();
|
34 |
|
|
}
|
35 |
|
|
}
|
36 |
|
|
|
37 |
|
|
/**
|
38 |
|
|
* @param args
|
39 |
|
|
*/
|
40 |
|
|
public static void main(String[] args) throws Exception {
|
41 |
|
|
HttpServer server;
|
42 |
|
|
InetSocketAddress adr = new InetSocketAddress("127.0.0.1", 9999);
|
43 |
|
|
server = HttpServer.create(adr, 20);
|
44 |
|
|
server.createContext("/", new TestListener() );
|
45 |
|
|
server.start();
|
46 |
|
|
System.out.println("Server is running");
|
47 |
|
|
while (true) {
|
48 |
|
|
Thread.sleep(10);
|
49 |
|
|
}
|
50 |
|
|
|
51 |
|
|
}
|
52 |
|
|
|
53 |
|
|
}
|