Android进阶之路Android技术知识Android开发

Android使用AsyncHttpServer实现本地HTTP

2019-08-22  本文已影响5人  手指乐

引入AsyncHttpServer

compile 'com.koushikdutta.async:androidasync:2.2.1'

封装实现类

public class LocalHttpServer implements HttpServerRequestCallback {

    private static final String TAG = "LocalHttpServer";

    private static LocalHttpServer mInstance;

    public static int PORT_LISTEN_DEFALT = 5000;

    AsyncHttpServer server = new AsyncHttpServer();

    public static LocalHttpServer getInstance() {
        if (mInstance == null) {
            //增加类锁,保证只初始化一次
            synchronized (LocalHttpServer.class) {
                if (mInstance == null) {
                    mInstance = new LocalHttpServer();
                }
            }
        }
        return mInstance;
    }


    public void stopServer(){
        server.stop();
    }


    public void startServer() {
        server.addAction("OPTIONS", "[\\d\\D]*", this);
        server.get("[\\d\\D]*", this);
        server.post("[\\d\\D]*", this);
        server.listen(PORT_LISTEN_DEFALT);

    }

    @Override
    public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        Log.d(TAG, "come in");
        String uri = request.getPath();
        Log.d(TAG, "uri="+uri);
    }
}

server.addAction("OPTIONS", "[\d\D]*", this);--所有的option请求都调用本来的onRequest回调
后面的 server.get, server.post类似于addAction("get",....) addAction("post",....)
server.listen(PORT_LISTEN_DEFALT);--在指定端口监听

上一篇下一篇

猜你喜欢

热点阅读