Java Sun HttpServer无法提供数据

时间:2014-10-28 02:40:47

标签: java http webserver handler httphandler

以下内容应该在localhost上提供一些文本:8080 / 然而,似乎没有任何事情发生。它不会触发任何异常,编译正常,不会崩溃等等......但是从不调用处理程序。我正在使用薄荷Linux。

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.*;

public class MyServer {
    @SuppressWarnings("restriction")
    public class MyHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            System.out.println("Request received.");
            String response = "<html><body>Hello world!</body></html>";
            exchange.sendResponseHeaders(200, response.length());
            exchange.getResponseBody().write(response.getBytes());
            exchange.close();                
        }

    }

    @SuppressWarnings("restriction")
    private HttpServer server;

    @SuppressWarnings("restriction")
    public MyServer() throws IOException {
        server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 100);
        server.createContext("/", new MyHandler());
        server.setExecutor(null);
    }

    @SuppressWarnings("restriction")
    public void start() {
        server.start();
    }

    public static void main(String args[]) {
        try {    
            System.out.println("Starting...");
            MyServer ms = new MyServer();
            ms.start();
            System.out.println("Started.");
        } catch(Exception e) {
            e.printStackTrace();
        }

    }
}

0 个答案:

没有答案