Android应用程序中创建一个http服务器

采用NanoHTTPD框架
想明白原理的,请右转—>原文github地址 :https://github.com/NanoHttpd/nanohttpd

本文主要向您展示如何在Android应用程序中创建一个http服务器。

加入依赖包

   implementation 'org.nanohttpd:nanohttpd:2.3.1'

添加权限申请

    
    
    
    
    

主界面程序

mport android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.net.SocketException;

public class MainActivity extends AppCompatActivity {
    private MyAppServer mywebserver;
    private TextView ipAddress;

    @Override
    public void onCreate( Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ipAddress = findViewById(R.id.ipAddress);
        String localIPAddress = null;
        try {
            localIPAddress = GetLocalIp.getLocalIPAddress();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        ipAddress.setText("当前设备ip地址为:"+localIPAddress+":33445");
        Log.e("localIPAddress",localIPAddress+"");
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            mywebserver = new MyAppServer(this);
            Log.e("onResume", "WebServer started");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("onResume", "WebServer start failed" + e.getMessage());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mywebserver != null) {
            mywebserver.closeAllConnections();
            mywebserver = null;
            Log.e("onPause", "app pause, so web server close");
        }
    }

}

server类


import android.content.Context;
import java.io.IOException;
import java.util.Map;
import fi.iki.elonen.NanoHTTPD;

public class MyAppServer extends NanoHTTPD {
    private final static int PORT = 33445;//自定义
    private Context _mainContext;

    public MyAppServer(Context context) throws IOException {
        super(PORT);
        _mainContext = context;
        start();
        System.out.println("\nRunning! Point your browsers to [http://0.0.0.0:33445/](http://localhost:33445/)\n");
    }

    @Override
    public Response serve(IHTTPSession session) {
        String msg = "

Hello server

\n"; Map parms = session.getParms(); if (parms.get("username") == null) { msg += "
\n

Your name:

\n" + "
\n"; } else { msg += "

Hello, " + parms.get("username") + "!

"; } return newFixedLengthResponse(msg + "\n"); } }

获取本机ip


import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class GetLocalIp {

    /**
     * 获取IP地址
     * @return
     * @throws SocketException
     */
    public static String getLocalIPAddress() throws SocketException {
        for(Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
            NetworkInterface intf = en.nextElement();
            for(Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
                InetAddress inetAddress = enumIpAddr.nextElement();
                if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
        return "null";
    }



}

成功在android设备中启动,获取IP后,即可在网站进行访问。
Android应用程序中创建一个http服务器_第1张图片
请求后的返回
Android应用程序中创建一个http服务器_第2张图片

你可能感兴趣的:(Android)