The introduction
NanoHTTPD is a free, lightweight HTTP Server implemented in Java that can be easily integrated into Android applications, implementing a lightweight Web Server.
steps
Create a Server on the client side,
public class SimpleServer extends NanoHTTPD {
public SimpleServer(int port) {
super(port);
}
@Override
public Response serve(IHTTPSession session) {
StringBuilder builder = new StringBuilder();
builder.append("
");
builder.append("<p>Hello! This Android HTTP Server.</p>");
builder.append("<h1>:)</h1></body></html>\n");
returnnewFixedLengthResponse(builder.toString()); }}Copy the code
Create a piece of code in the Inherited page Activity class to enable the server
public class MainActivity extends Activity {
private SimpleServer server;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Access address: http://127.0.0.1:8080
server = new SimpleServer(8080);
try {
// Because the application emulates HTML placed in the asset directory,
// Store the AssetManager pointer here.
server.asset_mgr = this.getAssets();
// Start the Web service
server.start();
Log.i("Httpd"."The server started.");
} catch(IOException ioe) {
Log.w("Httpd"."The server could not start."); }}}Copy the code
Finally, using NanoHTTPD requires adding network permissions
<uses-permission android:name="android.permission.INTERNET"/>Copy the code
The test access address is http://127.0.0.1:8080
Reference:
- Android uses NanoHttpd to build servers
- Use NanoHTTPD to set up local server points on Android
- Nanohttpd-2.3.1. jar download address here