目前在 Android 上启用 HTTP Server 的开源库有两个：
One of the main difference between the two is that NanoHTTPD is using threads while AndroidAsync is based on NIO. I can’t tell you which one is better in terms of speed as I didn’t test this yet, but I will let you know as soon as I have more data on both.
Let’s start coding
Before starting the exciting coding make sure you add the following code to your AndroidManifest.xml file:
For this project I also used Gradle. So in order to add AndroidAsync to your project add the following line to your build.gradle file:
Now let’s modify MainActivity.java accordingly:
Now start the application and after go to your device’s browser or to your emulator’s browser and type http://localhost:8080/ and you should see:
I assume the code above is pretty self explanatory and it doesn’t need too much description. But what I did was to add a new AsyncHttpServer and handled a GET request to which we respond with the String “Hello!!!”. Also we made our server to listen on port 8080. You can choose any port you want.
I suggest you create a separate class that handles all the server methods. In this case I have added it in the MainActivity.java for convenience purposes.
In order to stop the server you have to call the following methods:
That’s about it. If you need further examples using NanoHTTPD or AndroidAsync please let me know in the comments bellow and will come with more in detail examples.
You can find the full project on GitHub here.
Another challenge of using it would be how to parse the request body of a request coming from a REST client.
In order to test the code I recommend installing RESTClient for Firefox or any REST client for the browser that you use. This will help us send the request to our server that we have previously created.
Lets also send as a JSON request the example bellow:
Let’s add the following piece of code to the startServer() method that we created:
Now go open your browser, enter the REST client and type in: your.tablet.ip:8080/testJSON, with HTTP method POST and in the request body paste the JSON object above. If all works well you should see in the Response field the value File.
A question that may come up from the code above is why the JSON transformation? Well, JSON is a format that is very easy to work with and I find it very practical to work with JSON objects. On the other hand the method above is performant and makes sense only if you know for sure that you will receive JSON format on you request object. If not use the parsing methods in the AsyncHttpRequestBody class.
Please let me know if there is any other part of the AndroidAsync that you want me to cover in a future post.
You can also find the complete code here .