assets需要是内部类才可访问
在MainActivity
中继承NanoHTTPD
:
inner class HttpServer(port: Int) : NanoHTTPD(port) {
override fun handle(session: IHTTPSession): Response {
try {
val file = assets.open(session.uri.toString().substring(1)).buffered()
return Response.newChunkedResponse(
Status.OK,
"text/html",
file)
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
} catch (e: ResponseException) {
e.printStackTrace()
}
return response404(session, session.uri)
}
//页面不存在,或者文件不存在时
private fun response404(
session: IHTTPSession?,
url: String?
): Response {
return Response.newFixedLengthResponse("<!DOCTYPE html><html><body>Sorry, We Can't Find $url !</body></html>\n")
}
}
开启服务器使用如下代码:
HttpServer(port).Start()