Last active
November 26, 2018 22:57
-
-
Save chris-piekarski/cf9d6e1ef5416270591647b144e18218 to your computer and use it in GitHub Desktop.
Using NanoHTTPD in Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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