Package fi.iki.elonen
Class NanoHTTPD
- java.lang.Object
-
- fi.iki.elonen.NanoHTTPD
-
- Direct Known Subclasses:
DebugServer
,HelloServer
,NanoWSD
,RouterNanoHTTPD
,SimpleWebServer
public abstract class NanoHTTPD extends java.lang.Object
A simple, tiny, nicely embeddable HTTP server in Java NanoHTTPDCopyright (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 Classes Modifier and Type Class Description static interface
NanoHTTPD.AsyncRunner
Pluggable strategy for asynchronously executing requests.class
NanoHTTPD.ClientHandler
The runnable that will be used for every new client connection.protected static class
NanoHTTPD.ContentType
static class
NanoHTTPD.Cookie
class
NanoHTTPD.CookieHandler
Provides rudimentary support for cookies.static class
NanoHTTPD.DefaultAsyncRunner
Default threading strategy for NanoHTTPD.static class
NanoHTTPD.DefaultServerSocketFactory
Creates a normal ServerSocket for TCP connectionsstatic class
NanoHTTPD.DefaultTempFile
Default strategy for creating and cleaning up temporary files.static class
NanoHTTPD.DefaultTempFileManager
Default strategy for creating and cleaning up temporary files.private class
NanoHTTPD.DefaultTempFileManagerFactory
Default strategy for creating and cleaning up temporary files.protected class
NanoHTTPD.HTTPSession
static interface
NanoHTTPD.IHTTPSession
Handles one session, i.e.static class
NanoHTTPD.Method
HTTP Request methods, with the ability to decode aString
back to its enum value.static class
NanoHTTPD.Response
HTTP response.static class
NanoHTTPD.ResponseException
static class
NanoHTTPD.SecureServerSocketFactory
Creates a new SSLServerSocketclass
NanoHTTPD.ServerRunnable
The runnable that will be used for the main listening thread.static interface
NanoHTTPD.ServerSocketFactory
Factory to create ServerSocketFactories.static interface
NanoHTTPD.TempFile
A temp file.static interface
NanoHTTPD.TempFileManager
Temp file manager.static interface
NanoHTTPD.TempFileManagerFactory
Factory to create temp file managers.
-
Field Summary
Fields Modifier and Type Field Description protected NanoHTTPD.AsyncRunner
asyncRunner
Pluggable strategy for asynchronously executing requests.private static java.util.regex.Pattern
CONTENT_DISPOSITION_ATTRIBUTE_PATTERN
private static java.lang.String
CONTENT_DISPOSITION_ATTRIBUTE_REGEX
private static java.util.regex.Pattern
CONTENT_DISPOSITION_PATTERN
private static java.lang.String
CONTENT_DISPOSITION_REGEX
private static java.util.regex.Pattern
CONTENT_TYPE_PATTERN
private static java.lang.String
CONTENT_TYPE_REGEX
private java.lang.String
hostname
private static java.util.logging.Logger
LOG
logger to log to.static java.lang.String
MIME_HTML
Common MIME type for dynamic content: htmlstatic java.lang.String
MIME_PLAINTEXT
Common MIME type for dynamic content: plain textprotected static java.util.Map<java.lang.String,java.lang.String>
MIME_TYPES
Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPEprivate int
myPort
private java.net.ServerSocket
myServerSocket
private java.lang.Thread
myThread
private static java.lang.String
QUERY_STRING_PARAMETER
Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing.private NanoHTTPD.ServerSocketFactory
serverSocketFactory
static int
SOCKET_READ_TIMEOUT
Maximum 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.TempFileManagerFactory
tempFileManagerFactory
Pluggable strategy for creating and cleaning up temporary files.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
closeAllConnections()
Forcibly closes all connections that are open.protected NanoHTTPD.ClientHandler
createClientHandler(java.net.Socket finalAccept, java.io.InputStream inputStream)
create a instance of the client handler, subclasses can return a subclass of the ClientHandler.protected NanoHTTPD.ServerRunnable
createServerRunnable(int timeout)
Instantiate the server runnable, can be overwritten by subclasses to provide a subclass of the ServerRunnable.protected static java.util.Map<java.lang.String,java.util.List<java.lang.String>>
decodeParameters(java.lang.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.protected static java.util.Map<java.lang.String,java.util.List<java.lang.String>>
decodeParameters(java.util.Map<java.lang.String,java.lang.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 java.lang.String
decodePercent(java.lang.String str)
Decode percent encodedString
values.java.lang.String
getHostname()
int
getListeningPort()
static java.lang.String
getMimeTypeForFile(java.lang.String uri)
Get MIME type from file name extension, if possibleNanoHTTPD.ServerSocketFactory
getServerSocketFactory()
NanoHTTPD.TempFileManagerFactory
getTempFileManagerFactory()
boolean
isAlive()
private static void
loadMimeTypes(java.util.Map<java.lang.String,java.lang.String> result, java.lang.String resourceName)
void
makeSecure(javax.net.ssl.SSLServerSocketFactory sslServerSocketFactory, java.lang.String[] sslProtocols)
Call before start() to serve over HTTPS instead of HTTPstatic javax.net.ssl.SSLServerSocketFactory
makeSSLSocketFactory(java.lang.String keyAndTrustStoreClasspathPath, char[] passphrase)
Creates an SSLSocketFactory for HTTPS.static javax.net.ssl.SSLServerSocketFactory
makeSSLSocketFactory(java.security.KeyStore loadedKeyStore, javax.net.ssl.KeyManager[] keyManagers)
Creates an SSLSocketFactory for HTTPS.static javax.net.ssl.SSLServerSocketFactory
makeSSLSocketFactory(java.security.KeyStore loadedKeyStore, javax.net.ssl.KeyManagerFactory loadedKeyFactory)
Creates an SSLSocketFactory for HTTPS.static java.util.Map<java.lang.String,java.lang.String>
mimeTypes()
static NanoHTTPD.Response
newChunkedResponse(NanoHTTPD.Response.IStatus status, java.lang.String mimeType, java.io.InputStream data)
Create a response with unknown length (using HTTP 1.1 chunking).static NanoHTTPD.Response
newFixedLengthResponse(NanoHTTPD.Response.IStatus status, java.lang.String mimeType, java.io.InputStream data, long totalBytes)
Create a response with known length.static NanoHTTPD.Response
newFixedLengthResponse(NanoHTTPD.Response.IStatus status, java.lang.String mimeType, java.lang.String txt)
Create a text response with known length.static NanoHTTPD.Response
newFixedLengthResponse(java.lang.String msg)
Create a text response with known length.private static void
safeClose(java.lang.Object closeable)
NanoHTTPD.Response
serve(NanoHTTPD.IHTTPSession session)
Override this to customize the server.NanoHTTPD.Response
serve(java.lang.String uri, NanoHTTPD.Method method, java.util.Map<java.lang.String,java.lang.String> headers, java.util.Map<java.lang.String,java.lang.String> parms, java.util.Map<java.lang.String,java.lang.String> files)
Deprecated.void
setAsyncRunner(NanoHTTPD.AsyncRunner asyncRunner)
Pluggable strategy for asynchronously executing requests.void
setServerSocketFactory(NanoHTTPD.ServerSocketFactory serverSocketFactory)
void
setTempFileManagerFactory(NanoHTTPD.TempFileManagerFactory tempFileManagerFactory)
Pluggable strategy for creating and cleaning up temporary files.void
start()
Start the server.void
start(int timeout)
Starts the server (in setDaemon(true) mode).void
start(int timeout, boolean daemon)
Start the server.void
stop()
Stop the server.protected boolean
useGzipWhenAccepted(NanoHTTPD.Response r)
boolean
wasStarted()
-
-
-
Field Detail
-
CONTENT_DISPOSITION_REGEX
private static final java.lang.String CONTENT_DISPOSITION_REGEX
- See Also:
- Constant Field Values
-
CONTENT_DISPOSITION_PATTERN
private static final java.util.regex.Pattern CONTENT_DISPOSITION_PATTERN
-
CONTENT_TYPE_REGEX
private static final java.lang.String CONTENT_TYPE_REGEX
- See Also:
- Constant Field Values
-
CONTENT_TYPE_PATTERN
private static final java.util.regex.Pattern CONTENT_TYPE_PATTERN
-
CONTENT_DISPOSITION_ATTRIBUTE_REGEX
private static final java.lang.String CONTENT_DISPOSITION_ATTRIBUTE_REGEX
- See Also:
- Constant Field Values
-
CONTENT_DISPOSITION_ATTRIBUTE_PATTERN
private static final java.util.regex.Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN
-
SOCKET_READ_TIMEOUT
public static final int SOCKET_READ_TIMEOUT
Maximum 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:
- Constant Field Values
-
MIME_PLAINTEXT
public static final java.lang.String MIME_PLAINTEXT
Common MIME type for dynamic content: plain text- See Also:
- Constant Field Values
-
MIME_HTML
public static final java.lang.String MIME_HTML
Common MIME type for dynamic content: html- See Also:
- Constant Field Values
-
QUERY_STRING_PARAMETER
private static final java.lang.String QUERY_STRING_PARAMETER
Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing.- See Also:
- Constant Field Values
-
LOG
private static final java.util.logging.Logger LOG
logger to log to.
-
MIME_TYPES
protected static java.util.Map<java.lang.String,java.lang.String> MIME_TYPES
Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
-
hostname
private final java.lang.String hostname
-
myPort
private final int myPort
-
myServerSocket
private volatile java.net.ServerSocket myServerSocket
-
serverSocketFactory
private NanoHTTPD.ServerSocketFactory serverSocketFactory
-
myThread
private java.lang.Thread myThread
-
asyncRunner
protected NanoHTTPD.AsyncRunner asyncRunner
Pluggable strategy for asynchronously executing requests.
-
tempFileManagerFactory
private NanoHTTPD.TempFileManagerFactory tempFileManagerFactory
Pluggable strategy for creating and cleaning up temporary files.
-
-
Method Detail
-
mimeTypes
public static java.util.Map<java.lang.String,java.lang.String> mimeTypes()
-
loadMimeTypes
private static void loadMimeTypes(java.util.Map<java.lang.String,java.lang.String> result, java.lang.String resourceName)
-
makeSSLSocketFactory
public static javax.net.ssl.SSLServerSocketFactory makeSSLSocketFactory(java.security.KeyStore loadedKeyStore, javax.net.ssl.KeyManager[] keyManagers) throws java.io.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:
java.io.IOException
-
makeSSLSocketFactory
public static javax.net.ssl.SSLServerSocketFactory makeSSLSocketFactory(java.security.KeyStore loadedKeyStore, javax.net.ssl.KeyManagerFactory loadedKeyFactory) throws java.io.IOException
Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a loaded KeyManagerFactory. These objects must properly loaded/initialized by the caller.- Throws:
java.io.IOException
-
makeSSLSocketFactory
public static javax.net.ssl.SSLServerSocketFactory makeSSLSocketFactory(java.lang.String keyAndTrustStoreClasspathPath, char[] passphrase) throws java.io.IOException
Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your certificate and passphrase- Throws:
java.io.IOException
-
getMimeTypeForFile
public static java.lang.String getMimeTypeForFile(java.lang.String uri)
Get MIME type from file name extension, if possible- Parameters:
uri
- the string representing a file- Returns:
- the connected mime/type
-
safeClose
private static final void safeClose(java.lang.Object closeable)
-
closeAllConnections
public void closeAllConnections()
Forcibly closes all connections that are open.
-
createClientHandler
protected NanoHTTPD.ClientHandler createClientHandler(java.net.Socket finalAccept, java.io.InputStream inputStream)
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
protected NanoHTTPD.ServerRunnable createServerRunnable(int timeout)
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
protected static java.util.Map<java.lang.String,java.util.List<java.lang.String>> decodeParameters(java.util.Map<java.lang.String,java.lang.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. 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
protected static java.util.Map<java.lang.String,java.util.List<java.lang.String>> decodeParameters(java.lang.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. 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
protected static java.lang.String decodePercent(java.lang.String str)
Decode percent encodedString
values.- Parameters:
str
- the percent encodedString
- Returns:
- expanded form of the input, for example "foo%20bar" becomes "foo bar"
-
useGzipWhenAccepted
protected boolean useGzipWhenAccepted(NanoHTTPD.Response r)
- 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
public NanoHTTPD.ServerSocketFactory getServerSocketFactory()
-
setServerSocketFactory
public void setServerSocketFactory(NanoHTTPD.ServerSocketFactory serverSocketFactory)
-
getHostname
public java.lang.String getHostname()
-
getTempFileManagerFactory
public NanoHTTPD.TempFileManagerFactory getTempFileManagerFactory()
-
makeSecure
public void makeSecure(javax.net.ssl.SSLServerSocketFactory sslServerSocketFactory, java.lang.String[] sslProtocols)
Call before start() to serve over HTTPS instead of HTTP
-
newChunkedResponse
public static NanoHTTPD.Response newChunkedResponse(NanoHTTPD.Response.IStatus status, java.lang.String mimeType, java.io.InputStream data)
Create a response with unknown length (using HTTP 1.1 chunking).
-
newFixedLengthResponse
public static NanoHTTPD.Response newFixedLengthResponse(NanoHTTPD.Response.IStatus status, java.lang.String mimeType, java.io.InputStream data, long totalBytes)
Create a response with known length.
-
newFixedLengthResponse
public static NanoHTTPD.Response newFixedLengthResponse(NanoHTTPD.Response.IStatus status, java.lang.String mimeType, java.lang.String txt)
Create a text response with known length.
-
newFixedLengthResponse
public static NanoHTTPD.Response newFixedLengthResponse(java.lang.String msg)
Create a text response with known length.
-
serve
public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session)
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(java.lang.String uri, NanoHTTPD.Method method, java.util.Map<java.lang.String,java.lang.String> headers, java.util.Map<java.lang.String,java.lang.String> parms, java.util.Map<java.lang.String,java.lang.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.parms
- Parsed, percent decoded parameters from URI and, in case of POST, data.headers
- Header entries, percent decoded- Returns:
- HTTP response, see class Response for details
-
setAsyncRunner
public void setAsyncRunner(NanoHTTPD.AsyncRunner asyncRunner)
Pluggable strategy for asynchronously executing requests.- Parameters:
asyncRunner
- new strategy for handling threads.
-
setTempFileManagerFactory
public void setTempFileManagerFactory(NanoHTTPD.TempFileManagerFactory tempFileManagerFactory)
Pluggable strategy for creating and cleaning up temporary files.- Parameters:
tempFileManagerFactory
- new strategy for handling temp files.
-
start
public void start() throws java.io.IOException
Start the server.- Throws:
java.io.IOException
- if the socket is in use.
-
start
public void start(int timeout) throws java.io.IOException
Starts the server (in setDaemon(true) mode).- Throws:
java.io.IOException
-
start
public void start(int timeout, boolean daemon) throws java.io.IOException
Start the server.- Parameters:
timeout
- timeout to use for socket connections.daemon
- start the thread daemon or not.- Throws:
java.io.IOException
- if the socket is in use.
-
stop
public void stop()
Stop the server.
-
wasStarted
public final boolean wasStarted()
-
-