Class NanoHTTPD
java.lang.Object
fi.iki.elonen.NanoHTTPD
- Direct Known Subclasses:
DebugServer, HelloServer, NanoWSD, RouterNanoHTTPD, SimpleWebServer
A simple, tiny, nicely embeddable HTTP server in Java
NanoHTTPD
Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias
Features + limitations:- Only one Java file
- Java 5 compatible
- Released as open source, Modified BSD licence
- No fixed config files, logging, authorization etc. (Implement yourself if you need them.)
- Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)
- Supports both dynamic content and file serving
- Supports file upload (since version 1.2, 2010)
- Supports partial content (streaming)
- Supports ETags
- Never caches anything
- Doesn't limit bandwidth, request time or simultaneous connections
- Default code serves files and shows all HTTP parameters and headers
- File server supports directory listing, index.html and index.htm
- File server supports partial content (streaming)
- File server supports ETags
- File server does the 301 redirection trick for directories without '/'
- File server supports simple skipping for files (continue download)
- File server serves also very long files without memory overhead
- Contains a built-in list of most common MIME types
- All header names are converted to lower case so they don't vary between browsers/clients
- Subclass and implement serve() and embed to your own program
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfacePluggable strategy for asynchronously executing requests.classThe runnable that will be used for every new client connection.protected static classstatic classclassProvides rudimentary support for cookies.static classDefault threading strategy for NanoHTTPD.static classCreates a normal ServerSocket for TCP connectionsstatic classDefault strategy for creating and cleaning up temporary files.static classDefault strategy for creating and cleaning up temporary files.private classDefault strategy for creating and cleaning up temporary files.protected classstatic interfaceHandles one session, i.e.static enumHTTP Request methods, with the ability to decode aStringback to its enum value.static classHTTP response.static final classstatic classCreates a new SSLServerSocketclassThe runnable that will be used for the main listening thread.static interfaceFactory to create ServerSocketFactories.static interfaceA temp file.static interfaceTemp file manager.static interfaceFactory to create temp file managers. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected NanoHTTPD.AsyncRunnerPluggable strategy for asynchronously executing requests.private static final Patternprivate static final Stringprivate static final Patternprivate static final Stringprivate static final Patternprivate static final Stringprivate final Stringprivate static final Loggerlogger to log to.static final StringCommon MIME type for dynamic content: htmlstatic final StringCommon MIME type for dynamic content: plain textHashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPEprivate final intprivate ServerSocketprivate Threadprivate static final StringPseudo-Parameter to use to store the actual query string in the parameters map for later re-processing.private NanoHTTPD.ServerSocketFactorystatic final intMaximum time to wait on Socket.getInputStream().read() (in milliseconds) This is required as the Keep-Alive HTTP connections would otherwise block the socket reading thread forever (or as long the browser is open).private NanoHTTPD.TempFileManagerFactoryPluggable strategy for creating and cleaning up temporary files. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidForcibly closes all connections that are open.protected NanoHTTPD.ClientHandlercreateClientHandler(Socket finalAccept, InputStream inputStream) create a instance of the client handler, subclasses can return a subclass of the ClientHandler.protected NanoHTTPD.ServerRunnablecreateServerRunnable(int timeout) Instantiate the server runnable, can be overwritten by subclasses to provide a subclass of the ServerRunnable.decodeParameters(String queryString) Decode parameters from a URL, handing the case where a single parameter name might have been supplied several times, by return lists of values.decodeParameters(Map<String, String> parms) Decode parameters from a URL, handing the case where a single parameter name might have been supplied several times, by return lists of values.protected static StringdecodePercent(String str) Decode percent encodedStringvalues.final intstatic StringgetMimeTypeForFile(String uri) Get MIME type from file name extension, if possiblefinal booleanisAlive()private static voidloadMimeTypes(Map<String, String> result, String resourceName) voidmakeSecure(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) Call before start() to serve over HTTPS instead of HTTPstatic SSLServerSocketFactorymakeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) Creates an SSLSocketFactory for HTTPS.static SSLServerSocketFactorymakeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) Creates an SSLSocketFactory for HTTPS.static SSLServerSocketFactorymakeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) Creates an SSLSocketFactory for HTTPS.static NanoHTTPD.ResponsenewChunkedResponse(NanoHTTPD.Response.IStatus status, String mimeType, InputStream data) Create a response with unknown length (using HTTP 1.1 chunking).static NanoHTTPD.ResponsenewFixedLengthResponse(NanoHTTPD.Response.IStatus status, String mimeType, InputStream data, long totalBytes) Create a response with known length.static NanoHTTPD.ResponsenewFixedLengthResponse(NanoHTTPD.Response.IStatus status, String mimeType, String txt) Create a text response with known length.static NanoHTTPD.ResponseCreate a text response with known length.private static final voidserve(NanoHTTPD.IHTTPSession session) Override this to customize the server.serve(String uri, NanoHTTPD.Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) Deprecated.voidsetAsyncRunner(NanoHTTPD.AsyncRunner asyncRunner) Pluggable strategy for asynchronously executing requests.voidsetServerSocketFactory(NanoHTTPD.ServerSocketFactory serverSocketFactory) voidsetTempFileManagerFactory(NanoHTTPD.TempFileManagerFactory tempFileManagerFactory) Pluggable strategy for creating and cleaning up temporary files.voidstart()Start the server.voidstart(int timeout) Starts the server (in setDaemon(true) mode).voidstart(int timeout, boolean daemon) Start the server.voidstop()Stop the server.protected booleanfinal boolean
-
Field Details
-
CONTENT_DISPOSITION_REGEX
- See Also:
-
CONTENT_DISPOSITION_PATTERN
-
CONTENT_TYPE_REGEX
- See Also:
-
CONTENT_TYPE_PATTERN
-
CONTENT_DISPOSITION_ATTRIBUTE_REGEX
- See Also:
-
CONTENT_DISPOSITION_ATTRIBUTE_PATTERN
-
SOCKET_READ_TIMEOUT
public static final int SOCKET_READ_TIMEOUTMaximum time to wait on Socket.getInputStream().read() (in milliseconds) This is required as the Keep-Alive HTTP connections would otherwise block the socket reading thread forever (or as long the browser is open).- See Also:
-
MIME_PLAINTEXT
Common MIME type for dynamic content: plain text- See Also:
-
MIME_HTML
-
QUERY_STRING_PARAMETER
Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing.- See Also:
-
LOG
logger to log to. -
MIME_TYPES
-
hostname
-
myPort
private final int myPort -
myServerSocket
-
serverSocketFactory
-
myThread
-
asyncRunner
Pluggable strategy for asynchronously executing requests. -
tempFileManagerFactory
Pluggable strategy for creating and cleaning up temporary files.
-
-
Constructor Details
-
NanoHTTPD
public NanoHTTPD(int port) Constructs an HTTP server on given port. -
NanoHTTPD
Constructs an HTTP server on given hostname and port.
-
-
Method Details
-
mimeTypes
-
loadMimeTypes
-
makeSSLSocketFactory
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an array of loaded KeyManagers. These objects must properly loaded/initialized by the caller.- Throws:
IOException
-
makeSSLSocketFactory
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a loaded KeyManagerFactory. These objects must properly loaded/initialized by the caller.- Throws:
IOException
-
makeSSLSocketFactory
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your certificate and passphrase- Throws:
IOException
-
getMimeTypeForFile
-
safeClose
-
closeAllConnections
public void closeAllConnections()Forcibly closes all connections that are open. -
createClientHandler
create a instance of the client handler, subclasses can return a subclass of the ClientHandler.- Parameters:
finalAccept- the socket the cleint is connected toinputStream- the input stream- Returns:
- the client handler
-
createServerRunnable
Instantiate the server runnable, can be overwritten by subclasses to provide a subclass of the ServerRunnable.- Parameters:
timeout- the socet timeout to use.- Returns:
- the server runnable.
-
decodeParameters
Decode parameters from a URL, handing the case where a single parameter name might have been supplied several times, by return lists of values. In general these lists will contain a single element.- Parameters:
parms- original NanoHTTPD parameters values, as passed to theserve()method.- Returns:
- a map of
String(parameter name) toList<String>(a list of the values supplied).
-
decodeParameters
Decode parameters from a URL, handing the case where a single parameter name might have been supplied several times, by return lists of values. In general these lists will contain a single element.- Parameters:
queryString- a query string pulled from the URL.- Returns:
- a map of
String(parameter name) toList<String>(a list of the values supplied).
-
decodePercent
-
useGzipWhenAccepted
- Returns:
- true if the gzip compression should be used if the client accespts it. Default this option is on for text content and off for everything. Override this for custom semantics.
-
getListeningPort
public final int getListeningPort() -
isAlive
public final boolean isAlive() -
getServerSocketFactory
-
setServerSocketFactory
-
getHostname
-
getTempFileManagerFactory
-
makeSecure
Call before start() to serve over HTTPS instead of HTTP -
newChunkedResponse
public static NanoHTTPD.Response newChunkedResponse(NanoHTTPD.Response.IStatus status, String mimeType, InputStream data) Create a response with unknown length (using HTTP 1.1 chunking). -
newFixedLengthResponse
public static NanoHTTPD.Response newFixedLengthResponse(NanoHTTPD.Response.IStatus status, String mimeType, InputStream data, long totalBytes) Create a response with known length. -
newFixedLengthResponse
public static NanoHTTPD.Response newFixedLengthResponse(NanoHTTPD.Response.IStatus status, String mimeType, String txt) Create a text response with known length. -
newFixedLengthResponse
Create a text response with known length. -
serve
Override this to customize the server. (By default, this returns a 404 "Not Found" plain text error response.)- Parameters:
session- The HTTP session- Returns:
- HTTP response, see class Response for details
-
serve
@Deprecated public NanoHTTPD.Response serve(String uri, NanoHTTPD.Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) Deprecated.Override this to customize the server. (By default, this returns a 404 "Not Found" plain text error response.)- Parameters:
uri- Percent-decoded URI without parameters, for example "/index.cgi"method- "GET", "POST" etc.headers- Header entries, percent decodedparms- Parsed, percent decoded parameters from URI and, in case of POST, data.- Returns:
- HTTP response, see class Response for details
-
setAsyncRunner
Pluggable strategy for asynchronously executing requests.- Parameters:
asyncRunner- new strategy for handling threads.
-
setTempFileManagerFactory
Pluggable strategy for creating and cleaning up temporary files.- Parameters:
tempFileManagerFactory- new strategy for handling temp files.
-
start
Start the server.- Throws:
IOException- if the socket is in use.
-
start
Starts the server (in setDaemon(true) mode).- Throws:
IOException
-
start
Start the server.- Parameters:
timeout- timeout to use for socket connections.daemon- start the thread daemon or not.- Throws:
IOException- if the socket is in use.
-
stop
public void stop()Stop the server. -
wasStarted
public final boolean wasStarted()
-