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 lowercase so they don't vary between browsers/clients
*
*
*
*
Ways to use:
*
*
Run as a standalone app, serves files and shows requests
*
Subclass serve() and embed to your own program
*
Call serveFile() from serve() with your own base directory
*
*
*
* See the end of the source file for distribution license
* (Modified BSD licence)
*/
public class NanoHTTPD
{
// ==================================================
// API parts
// ==================================================
/**
* Override this to customize the server.
*
* (By default, this delegates to serveFile() and allows directory listing.)
*
* @param uri Percent-decoded URI without parameters, for example "/index.cgi"
* @param method "GET", "POST" etc.
* @param parms Parsed, percent decoded parameters from URI and, in case of POST, data.
* @param header Header entries, percent decoded
* @return HTTP response, see class Response for details
*/
public Response serve( String uri, String method, Properties header, Properties parms, Properties files )
{
myOut.println( method + " '" + uri + "' " );
Enumeration> e = header.propertyNames();
while ( e.hasMoreElements())
{
String value = (String)e.nextElement();
myOut.println( " HDR: '" + value + "' = '" +
header.getProperty( value ) + "'" );
}
e = parms.propertyNames();
while ( e.hasMoreElements())
{
String value = (String)e.nextElement();
myOut.println( " PRM: '" + value + "' = '" +
parms.getProperty( value ) + "'" );
}
e = files.propertyNames();
while ( e.hasMoreElements())
{
String value = (String)e.nextElement();
myOut.println( " UPLOADED: '" + value + "' = '" +
files.getProperty( value ) + "'" );
}
return serveFile( uri, header, myRootDir, true );
}
/**
* HTTP response.
* Return one of these from serve().
*/
public class Response
{
/**
* Default constructor: response = HTTP_OK, data = mime = 'null'
*/
public Response()
{
this.status = HTTP_OK;
}
/**
* Basic constructor.
*/
public Response( String status, String mimeType, InputStream data )
{
this.status = status;
this.mimeType = mimeType;
this.data = data;
}
/**
* Convenience method that makes an InputStream out of
* given text.
*/
public Response( String status, String mimeType, String txt )
{
this.status = status;
this.mimeType = mimeType;
try
{
this.data = new ByteArrayInputStream( txt.getBytes("UTF-8"));
}
catch ( java.io.UnsupportedEncodingException uee )
{
uee.printStackTrace();
}
}
/**
* Adds given line to the header.
*/
public void addHeader( String name, String value )
{
header.put( name, value );
}
/**
* HTTP status code after processing, e.g. "200 OK", HTTP_OK
*/
public String status;
/**
* MIME type of content, e.g. "text/html"
*/
public String mimeType;
/**
* Data of the response, may be null.
*/
public InputStream data;
/**
* Headers for the HTTP response. Use addHeader()
* to add lines.
*/
public Properties header = new Properties();
}
/**
* Some HTTP response status codes
*/
public static final String
HTTP_OK = "200 OK",
HTTP_PARTIALCONTENT = "206 Partial Content",
HTTP_RANGE_NOT_SATISFIABLE = "416 Requested Range Not Satisfiable",
HTTP_REDIRECT = "301 Moved Permanently",
HTTP_NOTMODIFIED = "304 Not Modified",
HTTP_FORBIDDEN = "403 Forbidden",
HTTP_NOTFOUND = "404 Not Found",
HTTP_BADREQUEST = "400 Bad Request",
HTTP_INTERNALERROR = "500 Internal Server Error",
HTTP_NOTIMPLEMENTED = "501 Not Implemented";
/**
* Common mime types for dynamic content
*/
public static final String
MIME_PLAINTEXT = "text/plain",
MIME_HTML = "text/html",
MIME_DEFAULT_BINARY = "application/octet-stream",
MIME_XML = "text/xml";
// ==================================================
// Socket & server code
// ==================================================
/**
* Starts a HTTP server to given port.
* Throws an IOException if the socket is already in use
*/
public NanoHTTPD( int port, File wwwroot ) throws IOException
{
myTcpPort = port;
this.myRootDir = wwwroot;
myServerSocket = new ServerSocket( myTcpPort );
myThread = new Thread( new Runnable()
{
public void run()
{
try
{
while( true )
new HTTPSession( myServerSocket.accept());
}
catch ( IOException ioe )
{}
}
});
myThread.setDaemon( true );
myThread.start();
}
/**
* Stops the server.
*/
public void stop()
{
try
{
myServerSocket.close();
myThread.join();
}
catch ( IOException ioe ) {}
catch ( InterruptedException e ) {}
}
/**
* Starts as a standalone file server and waits for Enter.
*/
public static void main( String[] args )
{
myOut.println( "NanoHTTPD 1.25 (C) 2001,2005-2011 Jarno Elonen and (C) 2010 Konstantinos Togias\n" +
"(Command line options: [-p port] [-d root-dir] [--licence])\n" );
// Defaults
int port = 80;
File wwwroot = new File(".").getAbsoluteFile();
// Show licence if requested
for ( int i=0; i= 0 && size > 0 )
{
rlen = is.read(buf, 0, 512);
size -= rlen;
if (rlen > 0)
f.write(buf, 0, rlen);
}
// Get the raw body as a byte []
byte [] fbuf = f.toByteArray();
// Create a BufferedReader for easily reading it as string.
ByteArrayInputStream bin = new ByteArrayInputStream(fbuf);
BufferedReader in = new BufferedReader( new InputStreamReader(bin));
// If the method is POST, there may be parameters
// in data section, too, read it:
if ( method.equalsIgnoreCase( "POST" ))
{
String contentType = "";
String contentTypeHeader = header.getProperty("content-type");
StringTokenizer st = new StringTokenizer( contentTypeHeader , "; " );
if ( st.hasMoreTokens()) {
contentType = st.nextToken();
}
if (contentType.equalsIgnoreCase("multipart/form-data"))
{
// Handle multipart/form-data
if ( !st.hasMoreTokens())
sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html" );
String boundaryExp = st.nextToken();
st = new StringTokenizer( boundaryExp , "=" );
if (st.countTokens() != 2)
sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary syntax error. Usage: GET /example/file.html" );
st.nextToken();
String boundary = st.nextToken();
decodeMultipartData(boundary, fbuf, in, parms, files);
}
else
{
// Handle application/x-www-form-urlencoded
String postLine = "";
char pbuf[] = new char[512];
int read = in.read(pbuf);
while ( read >= 0 && !postLine.endsWith("\r\n") )
{
postLine += String.valueOf(pbuf, 0, read);
read = in.read(pbuf);
}
postLine = postLine.trim();
decodeParms( postLine, parms );
}
}
if ( method.equalsIgnoreCase( "PUT" ))
files.put("content", saveTmpFile( fbuf, 0, f.size()));
// Ok, now do the serve()
Response r = serve( uri, method, header, parms, files );
if ( r == null )
sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: Serve() returned a null response." );
else
sendResponse( r.status, r.mimeType, r.header, r.data );
in.close();
is.close();
}
catch ( IOException ioe )
{
try
{
sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
}
catch ( Throwable t ) {}
}
catch ( InterruptedException ie )
{
// Thrown by sendError, ignore and exit the thread.
}
}
/**
* Decodes the sent headers and loads the data into
* java Properties' key - value pairs
**/
private void decodeHeader(BufferedReader in, Properties pre, Properties parms, Properties header)
throws InterruptedException
{
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) return;
StringTokenizer st = new StringTokenizer( inLine );
if ( !st.hasMoreTokens())
sendError( HTTP_BADREQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html" );
String method = st.nextToken();
pre.put("method", method);
if ( !st.hasMoreTokens())
sendError( HTTP_BADREQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html" );
String uri = st.nextToken();
// Decode parameters from the URI
int qmi = uri.indexOf( '?' );
if ( qmi >= 0 )
{
decodeParms( uri.substring( qmi+1 ), parms );
uri = decodePercent( uri.substring( 0, qmi ));
}
else uri = decodePercent(uri);
// If there's another token, it's protocol version,
// followed by HTTP headers. Ignore version but parse headers.
// NOTE: this now forces header names lowercase since they are
// case insensitive and vary by client.
if ( st.hasMoreTokens())
{
String line = in.readLine();
while ( line != null && line.trim().length() > 0 )
{
int p = line.indexOf( ':' );
if ( p >= 0 )
header.put( line.substring(0,p).trim().toLowerCase(), line.substring(p+1).trim());
line = in.readLine();
}
}
pre.put("uri", uri);
}
catch ( IOException ioe )
{
sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
}
}
/**
* Decodes the Multipart Body data and put it
* into java Properties' key - value pairs.
**/
private void decodeMultipartData(String boundary, byte[] fbuf, BufferedReader in, Properties parms, Properties files)
throws InterruptedException
{
try
{
int[] bpositions = getBoundaryPositions(fbuf,boundary.getBytes());
int boundarycount = 1;
String mpline = in.readLine();
while ( mpline != null )
{
if (mpline.indexOf(boundary) == -1)
sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html" );
boundarycount++;
Properties item = new Properties();
mpline = in.readLine();
while (mpline != null && mpline.trim().length() > 0)
{
int p = mpline.indexOf( ':' );
if (p != -1)
item.put( mpline.substring(0,p).trim().toLowerCase(), mpline.substring(p+1).trim());
mpline = in.readLine();
}
if (mpline != null)
{
String contentDisposition = item.getProperty("content-disposition");
if (contentDisposition == null)
{
sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html" );
}
StringTokenizer st = new StringTokenizer( contentDisposition , "; " );
Properties disposition = new Properties();
while ( st.hasMoreTokens())
{
String token = st.nextToken();
int p = token.indexOf( '=' );
if (p!=-1)
disposition.put( token.substring(0,p).trim().toLowerCase(), token.substring(p+1).trim());
}
String pname = disposition.getProperty("name");
pname = pname.substring(1,pname.length()-1);
String value = "";
if (item.getProperty("content-type") == null) {
while (mpline != null && mpline.indexOf(boundary) == -1)
{
mpline = in.readLine();
if ( mpline != null)
{
int d = mpline.indexOf(boundary);
if (d == -1)
value+=mpline;
else
value+=mpline.substring(0,d-2);
}
}
}
else
{
if (boundarycount> bpositions.length)
sendError( HTTP_INTERNALERROR, "Error processing request" );
int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount-2]);
String path = saveTmpFile(fbuf, offset, bpositions[boundarycount-1]-offset-4);
files.put(pname, path);
value = disposition.getProperty("filename");
value = value.substring(1,value.length()-1);
do {
mpline = in.readLine();
} while (mpline != null && mpline.indexOf(boundary) == -1);
}
parms.put(pname, value);
}
}
}
catch ( IOException ioe )
{
sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
}
}
/**
* Find the byte positions where multipart boundaries start.
**/
public int[] getBoundaryPositions(byte[] b, byte[] boundary)
{
int matchcount = 0;
int matchbyte = -1;
Vector matchbytes = new Vector();
for (int i=0; i 0)
{
String tmpdir = System.getProperty("java.io.tmpdir");
try {
File temp = File.createTempFile("NanoHTTPD", "", new File(tmpdir));
OutputStream fstream = new FileOutputStream(temp);
fstream.write(b, offset, len);
fstream.close();
path = temp.getAbsolutePath();
} catch (Exception e) { // Catch exception if any
myErr.println("Error: " + e.getMessage());
}
}
return path;
}
/**
* It returns the offset separating multipart file headers
* from the file's data.
**/
private int stripMultipartHeaders(byte[] b, int offset)
{
int i = 0;
for (i=offset; i
* For example: "an+example%20string" -> "an example string"
*/
private String decodePercent( String str ) throws InterruptedException
{
try
{
StringBuffer sb = new StringBuffer();
for( int i=0; i= 0 )
p.put( decodePercent( e.substring( 0, sep )).trim(),
decodePercent( e.substring( sep+1 )));
}
}
/**
* Returns an error message as a HTTP response and
* throws InterruptedException to stop further request processing.
*/
private void sendError( String status, String msg ) throws InterruptedException
{
sendResponse( status, MIME_PLAINTEXT, null, new ByteArrayInputStream( msg.getBytes()));
throw new InterruptedException();
}
/**
* Sends given response to the socket.
*/
private void sendResponse( String status, String mime, Properties header, InputStream data )
{
try
{
if ( status == null )
throw new Error( "sendResponse(): Status can't be null." );
OutputStream out = mySocket.getOutputStream();
PrintWriter pw = new PrintWriter( out );
pw.print("HTTP/1.0 " + status + " \r\n");
if ( mime != null )
pw.print("Content-Type: " + mime + "\r\n");
if ( header == null || header.getProperty( "Date" ) == null )
pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");
if ( header != null )
{
Enumeration