HttpServer源码

/**<pre>
Provides a simple high-level Http server API, which can be used to build embedded HTTP servers. 
Both "http" and "https" are supported. 
The API provides a partial implementation of RFC 2616 (HTTP 1.1) and RFC 2818 (HTTP over TLS). 
Any HTTP functionality not provided by this API can be implemented by application code 
using the API. 

Programmers must implement the HttpHandler interface. 
This interface provides a callback which is invoked to handle incoming requests from clients. 
A HTTP request and its response is known as an exchange.

The HttpServer class is used to listen for incoming TCP connections and it dispatches requests 
on these connections to handlers which have been registered with the server.

For sensitive information, a HttpsServer can be used to process "https" requests secured by the SSL or 
TLS protocols. A HttpsServer must be provided with a HttpsConfigurator object, 
which contains an initialized SSLContext. HttpsConfigurator can be used to configure the cipher suites and 
other SSL operating parameters. A simple example SSLContext could be created as follows: 

char[] passphrase = "passphrase".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("testkeys"), passphrase);

KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);

TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);

SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

The following code shows how the SSLContext is then used in a HttpsConfigurator and how the SSLContext 
and HttpsConfigurator are linked to the HttpsServer.  

server.setHttpsConfigurator (new HttpsConfigurator(sslContext) {
    public void configure (HttpsParameters params) {

    // get the remote address if needed
    InetSocketAddress remote = params.getClientAddress();

    SSLContext c = getSSLContext();

    // get the default parameters
    SSLParameters sslparams = c.getDefaultSSLParameters();
    if (remote.equals (...) ) {
        // modify the default set for client x
    }

    params.setSSLParameters(sslparams);
    // statement above could throw IAE if any params invalid.
    // eg. if app has a UI and parameters supplied by a user.

    }
});
</pre> */

public class HttpServerDemo {
    public static void main(String[] args) throws IOException {
        startHttpServer();
    }

    static void startHttpServer() throws IOException {
        int port = 8888;
        InetSocketAddress addr = new InetSocketAddress(port);
        HttpServer server = HttpServer.create(addr, 0);

        server.createContext("/myApp", new MyHandler());

        //server.setExecutor(null); // creates a default executor
        server.setExecutor(Executors.newCachedThreadPool());
        server.start();
        System.out.println("Server is listening on port " + port + "...");
    }
}

class MyHandler implements HttpHandler {
    public void handle(HttpExchange exchange) throws IOException {
        String requestMethod = exchange.getRequestMethod();
        System.out.println("RequestMethod: " + requestMethod);

        if (requestMethod.equalsIgnoreCase("GET")) {
            Headers responseHeaders = exchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/html"); //text/plain
            exchange.sendResponseHeaders(200, 0);

            OutputStream responseBody = exchange.getResponseBody();
            Headers requestHeaders = exchange.getRequestHeaders();
            Set<String> keySet = requestHeaders.keySet();
            Iterator<String> iter = keySet.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                List<String> values = requestHeaders.get(key);
                String s = "<b>" + key + "</b> = " + values.toString() + "<br>";
                responseBody.write(s.getBytes());
            }
            responseBody.close();
        }
    }
}

你可能感兴趣的:(http,server)