Android embedded web-server

北城余情 提交于 2019-12-23 00:39:03

问题


I want to embed a web-server in my android application where devices connecting to it will have two abilities. One is send an xml-file that I can parse and do some stuff and the other to be able to download a file from my sd-card.

I found nanoHTTPD and AndroidHTTPD etc but not good documentation and I'm facing problems especially on how to give the ability to download the File. Is there any good tutorial/example that handles files or an easy-to-use library except of the ones I noted above?


回答1:


Two things come to mind, both are permissions related. Take a look at your android manifest, you'll want two permissions for your app

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

INTERNET, because you're accessing network services, and WRITE_EXTERNAL_STORAGE because when NanoHttpd receives an incoming connection it writes temp files and most / all phones map the "java.io.tmpdir" to point at the SD card.

Create a class that extends the basic NanoHttpd, passing the socket that you want to run on, and then implement the abstract 'serve()' method.

When your client application uploads their XML file, be sure that it's sending in the standard Multipart form encoding, and the filename will be given to you in the "files" map parameter to serve().

When you send a response back to a client, new up a Response() object, and you can either hand it an InputStream (from your SD card file) or just a String for the content.

If you need documentation, in the form of examples, NanoHttpd includes a fully functional webserver that serves files, and what I call "DemoServer" which is great for debugging what client applications send. There arent any Android specific examples yet but the volume of questions suggests that I ought to add some. :)

Thanks. Hope this helps. Let me know if you have more questions.



来源:https://stackoverflow.com/questions/17964535/android-embedded-web-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!