HttpServer的使用

http://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/overview-summary.html

bedded HTTP servers.
bedded HTTP servers. Both "http" and "https" are supported. The API provides a partial implementation of RFC  (HTTP 1.1) and RFC  (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. HTTP exchanges are represented by the HttpExchange class. 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.

A minimal Http server example is shown below:

   class MyHandler implements HttpHandler {
       public void handle(HttpExchange t) throws IOException {
           InputStream is = t.getRequestBody();
           read(is); // .. read the request body
           String response = "This is the response";
           t.sendResponseHeaders(200,response.length());
           OutputStream os = t.getResponseBody();
           os.write(response.getBytes());
           os.close();
       }
   }
   ...

HttpServer server = HttpServer.create(new InetSocketAddress(8000));
server.createContext("/applications/myapp",new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();

The example above creates a simple HttpServer which uses the calling application thread to invoke the handle() method for incoming http requests directed to port 8000,and to the path /applications/myapp/.

The HttpExchange class encapsulates everything an application needs to process incoming requests and to generate appropriate responses.

Registering a handler with a HttpServer creates a HttpContext object and Filter objects can be added to the returned context. Filters are used to perform automatic pre- and post-processing of exchanges before they are passed to the exchange handler.

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 HttpsConfiguratorobject,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);

In the example above,a keystore file called "testkeys",created with the keytool utility is used as a certificate store for client and server certificates. 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 = p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>ms.getClientAddress();

    SSLContext c = getSSLContext();

    // get the default p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>meters
    SSLP<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>meters sslp<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>ms = c.getDefaultSSLP<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>meters();
    if (remote.equals (...) ) {
        // modify the default set for client x
    }

    p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>ms.setSSLP<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>meters(sslp<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>ms);
    // statement above <a href="https://www.jb51.cc/tag/Could/" target="_blank" class="keywords">Could</a> throw IAE if any p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>ms invalid.
    // eg. if app has a UI and p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>meters supplied by a user.

    }
});
1.6

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...