Android 做服务器NanoHTTPD使用

Android 应用内架设服务使用NanoHTTPD

github地址点击打开链接找到releases下载相应jar包导入到Android studio 中,添加网络权限,创建类继承NanoHTTPD,重写serve方法即可

public class HttpServer extends NanoHTTPD {
    public static final int DEFAULT_SERVER_PORT = 8020;
    private static final String REQUEST_ROOT = "/";

    private Handler mSelfHandler;
    private respBody mRespBody;

    private CutTicketDeviceThread mCutTicketDeviceThread;


    public HttpServer(Thread mThread) {
        super(DEFAULT_SERVER_PORT);

        //mylog.setFilename("HttpServer.log");
        mCutTicketDeviceThread = (CutTicketDeviceThread) mThread;
        mylog.debug(String.format("HttpServer创建 port=%d", DEFAULT_SERVER_PORT));

    }

    @Override
    public Response serve(IHTTPSession session) {
        Map header = session.getHeaders();
        if ("127.0.0.1".equals(header.get("http-client-ip")) & "/sale".equals(session.getUri())) {
            return responseSale(session);
        }
        if (REQUEST_ROOT.equals(session.getUri())) {
            mylog.error("客户端请求路径错误:" + REQUEST_ROOT);
            return responseRootPage(session);
        }

        mylog.error("客户端请求路径错误:" + session.getUri());
        return response404(session, session.getUri());
    }
 public Response response404(IHTTPSession session, String url) {
        StringBuilder builder = new StringBuilder();
        builder.append("");
        builder.append("Sorry, Can't Found " + url + " !");
        builder.append("\n");
        mylog.error(" return 404");
        return new Response(builder.toString());
    }
}

利用server启动服务

public class HttpService extends Service {

  
    private HttpServer mHttpServer;
    private boolean bServerStarted;

    private static Lock lock = new ReentrantLock();

    @Override
    public void onCreate()
    {
       
        bServerStarted=false;

        mylog.info( "HttpService Create.");
        return;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startServer();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        stopServer();
        super.onDestroy();
    }

    /**
     * Start server.
     */
    private void startServer() {
        if (mHttpServer != null  && !bServerStarted)
        {
            try {
                mHttpServer.start();
                bServerStarted = true;
                
            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            if(mHttpServer!=null)
            {
                mylog.info(String.format("Http服务已经启动了 mHttpServer=%s bServerStarted=%s  ....", mHttpServer.toString(), bServerStarted ? "true" : "false"));
            }
        }
        return;
    }


    /**
     * Stop server.
     */
    private void stopServer() {
        if (mHttpServer != null)
        {
            try {
                mHttpServer.stop();
                bServerStarted = false;
                mylog.info(  "mHttpServer Stop().....");
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return;
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

你可能感兴趣的:(Android)