// app/build.gradle中接入sdk
implementation 'org.nanohttpd:nanohttpd:2.3.1'
// 因为Android权限变更,此处使用应用外部私有存储
getExternalFilesDir("mgapkg")?.apply {
nanoHttpClient = MyNanoHttp(8090, absolutePath)
}
class MyNanoHttp(port:Int, private var rootPath:String): NanoHTTPD(port) {
private val fileNotExisted = """{"code": 1, "msg": "文件不存在"}"""
private val invalidParams = """{"code": 2, "msg": "参数错误"}"""
override fun serve(session: IHTTPSession?): Response {
val uri = session?.uri
return if (uri?.isNotEmpty() == true && uri.startsWith("/mgapkg/")) {
try {
val filePath = "$rootPath${uri.substring("/mgapkg".length)}"
val file = File(filePath)
if (file.exists()) {
newFixedLengthResponse(Response.Status.OK, getMimeTypeForFile(filePath), FileInputStream(filePath), file.length())
} else {
newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json", fileNotExisted)
}
} catch (ex:Throwable) {
newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json", fileNotExisted)
}
} else {
newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json", invalidParams)
}
}
}
http://localip:8090/mgapkg/path1/path2/filename
网友评论