NanoHTTPD Documentation

repository·master·Indexed 27 days ago

https://github.com/nanohttpd/nanohttpd

A lightweight, embeddable HTTP server for Java applications. NanoHTTPD provides a minimal core for building small services, file servers, and WebSocket implementations. It includes support for HTTPS with self-signed certificates, CORS configuration via the nanohttpd-webserver module, and specialized artifacts for WebSocket services and HTTP file servers.

Tokens
1.7K
Snippets
5
Records
5
Agent score
43%

What's inside NanoHTTPD

  1. Quickstart with SimpleWebServer

    master

    To quickly run a built-in HTTP file server using Maven, ensure you have Maven and the Java SDK installed, then execute the following commands from the project root:

    mvn compile
    mvn exec:java -pl webserver -Dexec.mainClass="org.nanohttpd.webserver.SimpleWebServer"

    The server will run on http://localhost:8080/.

    mvn compile
    mvn exec:java -pl webserver -Dexec.mainClass="org.nanohttpd.webserver.SimpleWebServer"
  2. Add NanoHTTPD dependencies (Maven and Gradle)

    master

    Depending on your use case, choose the appropriate artifact ID. Note that for versions 2.1.0 and earlier, the groupId was com.nanohttpd. For all newer versions, use org.nanohttpd.

    Specialized HTTP(S) Service

    Use artifactId: nanohttpd. Extend org.nanohttpd.NanoHTTPD.

    WebSocket Service

    Use artifactId: nanohttpd-websocket. Extend org.nanohttpd.NanoWebSocketServer.

    HTTP File Server

    Use artifactId: nanohttpd-webserver. Use org.nanohttpd.SimpleWebServer as a starting point.

    <!-- Maven: Specialized HTTP Service -->
    <dependency>
    	<groupId>org.nanohttpd</groupId>
    	<artifactId>nanohttpd</artifactId>
    	<version>CURRENT_VERSION</version>
    </dependency>
    
    <!-- Maven: WebSocket Service -->
    <dependency>
    	<groupId>org.nanohttpd</groupId>
    	<artifactId>nanohttpd-websocket</artifactId>
    	<version>CURRENT_VERSION</version>
    </dependency>
    
    <!-- Maven: File Server -->
    <dependency>
    	<groupId>org.nanohttpd</groupId>
    	<artifactId>nanohttpd-webserver</artifactId>
    	<version>CURRENT_VERSION</version>
    </dependency>
    
    <!-- Gradle Example -->
    dependencies {
    	runtime(
    		[group: 'org.nanohttpd', name: 'nanohttpd', version: 'CURRENT_VERSION'],
    	)
    }
  3. Enable HTTPS with a self-signed certificate

    master

    To serve HTTPS connections, you must generate a keystore and use server.makeSecure().

    1. Generate a keystore using keytool:
    keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048 -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999
    1. In your Java code, ensure keystore.jks is in your classpath and call makeSecure before starting the server:
    server.makeSecure(NanoHTTPD.makeSSLSocketFactory("/keystore.jks", "password".toCharArray()), null);
    keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048 -ext SAN=DNS:localhost,IP:127.0.0.1  -validity 9999
    
    server.makeSecure(NanoHTTPD.makeSSLSocketFactory("/keystore.jks", "password".toCharArray()), null);
  4. Create a custom web application by extending NanoHTTPD

    master

    To build a custom web application, extend the NanoHTTPD class and override the serve(IHTTPSession session) method to handle incoming requests.

    Note on Namespaces:

    • For NanoHTTPD < 3.0.0: Use fi.iki.elonen.NanoHTTPD.
    • For NanoHTTPD >= 3.0.0: Use org.nanohttpd.NanoHTTPD.

    Example implementation:

    package com.example;
    
    import java.io.IOException;
    import java.util.Map;
    
    import fi.iki.elonen.NanoHTTPD;
    // NOTE: If you're using NanoHTTPD >= 3.0.0 the namespace is different,
    //       instead of the above import use the following:
    // import org.nanohttpd.NanoHTTPD;
    
    public class App extends NanoHTTPD {
    
        public App() throws IOException {
            super(8080);
            start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
            System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
        }
    
        public static void main(String[] args) {
            try {
                new App();
            } catch (IOException ioe) {
                System.err.println("Couldn't start server:\n" + ioe);
            }
        }
    
        @Override
        public Response serve(IHTTPSession session) {
            String msg = "<html><body><h1">Hello server</h1>\n";
            Map<String, String> parms = session.getParms();
            if (parms.get("username") == null) {
                msg += "<form action='?' method='get'>\n  <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n";
            } else {
                msg += "<p>Hello, " + parms.get("username") + "!</p>";
            }
            return newFixedLengthResponse(msg + "</body></html>\n");
        }
    }
  5. Configure CORS in NanoHTTPD Webserver

    master

    The nanohttpd-webserver module supports Cross-Origin Resource Sharing (CORS). You can activate it using the --cors parameter.

    • --cors: Sets Access-Control-Allow-Origin to *. It defaults to serving Access-Control-Allow-Headers: origin,accept,content-type.
    • --cors=some_value: Sets Access-Control-Allow-Origin to the specified value.

    Examples:

    • Single origin: --cors=http://appOne.company.com
    • Multiple origins: --cors="http://appOne.company.com, http://appTwo.company.com" (use double quotes to treat as a single argument).

    To customize the allowed headers, set the System property AccessControlAllowHeader. Example: -DAccessControlAllowHeader=origin,accept,content-type,Authorization.

    --cors=http://appOne.company.com
    --cors="http://appOne.company.com, http://appTwo.company.com"
    -DAccessControlAllowHeader=origin,accept,content-type,Authorization