Class HttpServer

java.lang.Object
com.sun.net.httpserver.HttpServer
Direct Known Subclasses:
HttpsServer

public abstract class HttpServer extends Object
This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address. The sub-class HttpsServer implements a server which handles HTTPS requests.

One or more HttpHandler objects must be associated with a server in order to process requests. Each such HttpHandler is registered with a root URI path which represents the location of the application or service on this server. The mapping of a handler to a HttpServer is encapsulated by a HttpContext object. HttpContexts are created by calling createContext(String,HttpHandler). Any request for which no handler can be found is rejected with a 404 response. Management of threads can be done external to this object by providing a Executor object. If none is provided a default implementation is used.

Mapping request URIs to HttpContext paths

When a HTTP request is received, the appropriate HttpContext (and handler) is located by finding the context whose path is the longest matching prefix of the request URI's path. Paths are matched literally, which means that the strings are compared case sensitively, and with no conversion to or from any encoded forms. For example, given a HttpServer with the following HttpContexts configured:

description
Context Context path
ctx1"/"
ctx2"/apps/"
ctx3"/apps/foo/"

The following table shows some request URIs and which, if any context they would match with:

description
Request URI Matches context
"http://foo.com/apps/foo/bar"ctx3
"http://foo.com/apps/Foo/bar"no match, wrong case
"http://foo.com/apps/app1"ctx2
"http://foo.com/foo"ctx1

Note about socket backlogs

When binding to an address and port number, the application can also specify an integer backlog parameter. This represents the maximum number of incoming TCP connections which the system will queue internally. Connections are queued while they are waiting to be accepted by the HttpServer. When the limit is reached, further connections may be rejected (or possibly ignored) by the underlying TCP implementation. Setting the right backlog value is a compromise between efficient resource usage in the TCP layer (not setting it too high) and allowing adequate throughput of incoming requests (not setting it too low).

Since:
1.6