Skip to content

Instantly share code, notes, and snippets.

@chris-piekarski
Last active November 26, 2018 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-piekarski/cf9d6e1ef5416270591647b144e18218 to your computer and use it in GitHub Desktop.
Save chris-piekarski/cf9d6e1ef5416270591647b144e18218 to your computer and use it in GitHub Desktop.
Using NanoHTTPD in Android
Add your index.html file to res/raw
Add dep to app gradle file:
dependencies {
implementation 'org.nanohttpd:nanohttpd-webserver:2.3.1'
}
Java class file:
import fi.iki.elonen.NanoHTTPD;
public class BasicServer extends NanoHTTPD {
private Context mCtx;
public BasicServer(Context ctx) throws IOException {
super(8080);
mCtx = ctx;
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
@Override
public Response serve(IHTTPSession session) {
String uri = session.getUri();
if (uri.equalsIgnoreCase("/")) {
return snapshot(session);
}
return newFixedLengthResponse(Response.Status.NOT_FOUND,MIME_PLAINTEXT,"Not Found");
}
private Response indexFile(IHTTPSession session) {
InputStream x = mCtx.getResources().openRawResource(R.raw.index_html);
return newFixedLengthResponse(Response.Status.OK,"text/html", x, 2038);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment