app搭建HttpServer

在一些特殊的时候,需要在app端开一个http的服务,比如说像类似手机盒子的功能,然后其他子设备可以跟这个盒子进行通讯,完成一些功能。
最后本人选用的是nanohttpd这个开源库,只需要它的core中的代码就可以了,地址如下:
https://github.com/NanoHttpd/nanohttpd/tree/master/core

然后创建一个服务

@Override
    public void onCreate() {
        Log.i(TAG, "start httpService-->onCreate");
        super.onCreate();
        httpServer = new HttpServer(8080);
        try {
            httpServer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDestroy() {
        if (httpServer != null) {
            httpServer.stop();
        }
        super.onDestroy();
    }

然后创建httpserver类,进行请求的处理

public class HttpServer extends NanoHTTPD {
    private HttpController httpController;

    public HttpServer(int port) {
        super(port);
        httpController = new HttpController();
    }

    public HttpServer(String hostname, int port) {
        super(hostname, port);
    }

    @Override
    public Response handle(IHTTPSession session) {
        return super.handle(session);
    }

    @Override
    protected Response serve(IHTTPSession session) {
        Response response = Response.newFixedLengthResponse("valide request please check uri" + session.getUri());
        for (Method method : httpController.getClass().getMethods()) {
            HttpMethod annotaion = method.getAnnotation(HttpMethod.class);
            if (annotaion != null&&annotaion.value().equals(session.getUri())) {
                try {
                    response = (Response) method.invoke(httpController, session.getParameters());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
        return response;
    }
}

现在的业务中转是放在httpController类中,那么久可以根据不同的情况,设置不同的请求地址进行业务处理了

public class HttpController {
    private static final String TAG = "HttpController";

    /**
     * @return
     */
    @HttpMethod("/changeBg")
    public Response changeBg(Map> param) {
        Log.i(TAG, "changeBg--->" + new Gson().toJson(param));
        return Response.newFixedLengthResponse("success");
    }
}

注解类:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HttpMethod {
    String value();
}

最后用postman进行测试接口的功能
附上github地址
https://github.com/liangzs/httpServer/tree/master

你可能感兴趣的:(app搭建HttpServer)