我一直在玩 Java httpServer 类。当我运行我的测试应用程序时,它会以正确的方式到达 main 中的最后一行(println),但是在关闭应用程序之前它会在那里停留大约 45 秒。为什么它会这样做,有没有办法让它更快结束?谢谢
public class TestTester
{
public static void main(String[] args) throws IOException {
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8780);
HttpServer server = HttpServer.create(addr, 0);
server.createContext("/", new MyHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
URL url = new URL("http://localhost:8780/test");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStreamReader(connection.getInputStream()));
// print out the response headers
System.out.println("\nHttp Response Headers");
for (int i=0; ; i++)
{
String headerName = connection.getHeaderFieldKey(i);
String headerValue = connection.getHeaderField(i);
if (headerName == null && headerValue == null) {
// No more headers
break;
}
else if (headerName == null) {
System.out.println( " " + headerValue);
}
else
System.out.println( " " + headerName + ": " + headerValue );
}
connection.disconnect();
server.stop(0);
System.out.println("Stopped Server.");
} // end main()
}
class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException
{
System.out.println("===Enter MyHandler===");
System.out.println("Http Request Header:");
// print out the request methode and url
System.out.println( " " + exchange.getRequestMethod() + " "
+ exchange.getRequestURI() + " " + exchange.getProtocol());
// print out the request headers
Headers requestHeaders = exchange.getRequestHeaders();
for (String name : requestHeaders.keySet() )
{
List<String> values = requestHeaders.get(name);
for ( String value : values )
{
System.out.println( " " + name + ": " + value);
}
}
// print out the request body if any
BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
String sCurrentLine;
System.out.println( "\nHttp Request Body:");
if ( ! in.ready() )
System.out.println( " No Request Body");
else
{
while ((sCurrentLine = in.readLine()) != null) {
System.out.println(" " + sCurrentLine);
}
}
// set up and send response
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET"))
{
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/html");
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.write("<!DOCTYPE html><html><body><h1>My Response Header</h1><p>And some sample data.</p></body></html>".getBytes());
responseBody.close();
}
exchange.close();
} // end public void handle()
} // end class