package com.what21.httpserver.jdk16;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
public class MyHttpServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new MyHandler());
server.start();
}
}
package com.what21.httpserver.jdk16;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
public class MyHandler implements HttpHandler {
public void handle(HttpExchange xchg) throws IOException {
Headers headers = xchg.getRequestHeaders();
Set>> entries = headers.entrySet();
StringBuffer response = new StringBuffer();
for (Map.Entry> entry : entries){
response.append(entry.toString() + "\n");
}
// 返回
xchg.sendResponseHeaders(200, response.length());
OutputStream os = xchg.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}