在最近的项目中因为要用android作为一个服务器去做一个实时接收数据的功能,所以这个时候就要去做一个android本地的微型服务器。
那么此时我首先想到了spring boot,因为他是一个服务器的框架。但是实际上我们根本用不到这么大型的服务器框架,配置这些都太麻烦。所以,我又找到了ijetty、nanohttpd和androidasync这三个框架,都是比较微型的,适用于android的。
经过对比,ijetty使用起来过于复杂,而且会莫名其妙的报一些不太容易解决的问题,所以,舍弃掉了。
因为没仔细深究ijetty,所以就重点放到nanohttpd和androidasync;
那么就先来说下两个的优缺点:
1.nanohttpd是bio为底层封装的框架,而androidasync是nio为底层封装的,其他的是一样的,而且其实androidasync是仿照nanohttpd框架写的。所以,一定意义上来说,androidasync是nanohttpd的优化版,当然也要看具体应用场景辣。
2.nanohttpd只能用于httpserver,但是androidasync除了httpserver的应用还能用在websocket、httpclient等方面,其中从androidasync中脱离出来的ion的库也是比较有名的。
3.nanohttpd底层处理包含的返回状态码(例如: 200、300、400、500等)比较多;但是经过笔者阅读androidasync的源码发现,androidasync底层封装返回的状态码只有两种:200、404,正好笔者发现了这个坑(下面会讲到,options的例子)
下面看一下具体使用方法吧。
1.先说nanohttpd:
因为nanohttpd的框架实际就是一个单文件,可以直接去github上下载,下载地址
有了下载的文件,那么就可以继承这个文件写一个类,具体如下:
public class httpserver extends nanohttpd {
private static final string tag = "httpserver";
public static final string default_show_page = "index.html";
public static final int default_port = 9511;//此参数随便定义,最好定义1024-65535;1-1024是系统常用端口,1024-65535是非系统端口
public enum status implements response.istatus {
request_error(500, "请求失败"),
request_error_api(501, "无效的请求接口"),
request_error_cmd(502, "无效命令");
private final int requeststatus;
private final string description;
status(int requeststatus, string description) {
this.requeststatus = requeststatus;
this.description = description;
}
@override
public string getdescription() {
return description;
public int getrequeststatus() {
return requeststatus;
}
public httpserver() {//初始化端口
super(default_port);
@override
public response serve(ihttpsession session) {
string uri = session.geturi();
map<string, string> headers = session.getheaders();
//接收不到post参数的问题, http://blog.csdn.net/obguy/article/details/53841559
try {
session.parsebody(new hashmap<string, string>());
} catch (ioexception e) {
e.printstacktrace();
} catch (responseexception e) {
map<string, string> parms = session.getparms();
logutil.d(tag, uri);
//判断uri的合法性,自定义方法,这个是判断是否是接口的方法
if (checkuri(uri)) {
// 针对的是接口的处理
if (headers != null) {
logutil.d(tag, headers.tostring());
}
if (parms != null) {
logutil.d(tag, parms.tostring());
if (stringutil.isempty(uri)) {
throw new runtimeexception("无法获取请求地址");
if (method.options.equals(session.getmethod())) {
logutil.d(tag, "options探测性请求");
return addheaderresponse(response.status.ok);
switch (uri) {
case "/test": {//接口2
//此方法包括了封装返回的接口请求数据和处理异常以及跨域
return getxxx(parms);
}
default: {
return addheaderresponse(status.request_error_api);
} else {
//针对的是静态资源的处理
string filepath = getfilepath(uri); // 根据url获取文件路径
if (filepath == null) {
logutil.d(tag, "sd卡没有找到");
return super.serve(session);
file file = new file(filepath);
if (file != null && file.exists()) {
logutil.d(tag, "file path = " + file.getabsolutepath());
//根据文件名返回mimetype: image/jpg, video/mp4, etc
string mimetype = getmimetype(filepath);
response res = null;
inputstream is = new fileinputstream(file);
res = newfixedlengthresponse(response.status.ok, mimetype, is, is.available());
//下面是跨域的参数(因为一般要和h5联调,所以最好设置一下)
response.addheader("access-control-allow-headers", allowheaders);
response.addheader("access-control-allow-methods", "get, post, put, delete, head");
response.addheader("access-control-allow-credentials", "true");
response.addheader("access-control-allow-origin", "*");
response.addheader("access-control-max-age", "" + 42 * 60 * 60);
return res;
} else {
logutil.d(tag, "file path = " + file.getabsolutepath() + "的资源不存在");
}
} catch (exception e) {
//自己封装的返回请求
return addheaderrespose(status.request_error);
根据上面的例子,主要说以下几点: 1)请求都能接收到,无论post还是get,或者是其他请求,如果需要过滤则自己去处理;
2)注意上面处理的接收不到post参数的问题,已经给了参考链接在代码注释中,请查阅;
3)如果请求中既有接口又有静态资源(例如html),那注意区分两种请求,例如可以用uri去识别;当然返回都可以用流的形式,都可以调用api方法newfixedlengthresponse();
4)笔者建议,最好处理一下跨域的问题,因为是android有可能和h5联调,所以设置了跨域以后比较方便调试,当然某些场景也可以忽略,看个人需求;方法已经在以上代码中写了;
5)当然最后最重要的一点肯定是开启和关闭的代码了:
/**
* 开启本地网页点歌的服务
*/
public static void startlocalchoosemusicserver() {
if (httpserver == null) {
httpserver = new httpserver();
try {
// 启动web服务
if (!httpserver.isalive()) {
httpserver.start();
log.i(tag, "the server started.");
} catch (exception e) {
httpserver.stop();
log.e(tag, "the server could not start. e = " + e.tostring());
}
* 关闭本地服务
public static void quitchoosemusicserver() {
if (httpserver != null) {
if (httpserver.isalive()) {
httpserver.stop();
log.d(tag, "关闭局域网点歌的服务");
2再看一下androidasync: 这个框架就比较有意思了,功能也多,本文直说httpserver方面的相关知识,其余按下不表。
老规矩,先说用法: 在gradle中加入:
dependencies {
compile 'com.koushikdutta.async:androidasync:2.2.1'
代码示例:(此处没有处理跨域,如果需要的话,请根据上一个例子去处理)
public class niohttpserver implements httpserverrequestcallback {
private static final string tag = "niohttpserver";
private static niohttpserver minstance;
public static int port_listen_defalt = 5000;
asynchttpserver server = new asynchttpserver();
public static niohttpserver getinstance() {
if (minstance == null) {
// 增加类锁,保证只初始化一次
synchronized (niohttpserver.class) {
if (minstance == null) {
minstance = new niohttpserver();
return minstance;
//仿照nanohttpd的写法
public static enum status {
request_ok(200, "请求成功"),
request_error_cmd(502, "无效命令"),
request_error_deviceid(503, "不匹配的设备id"),
request_error_env(504, "不匹配的服务环境");
/**
* 开启本地服务
public void startserver() {
//如果有其他的请求方式,例如下面一行代码的写法
server.addaction("options", "[\\d\\d]*", this);
server.get("[\\d\\d]*", this);
server.post("[\\d\\d]*", this);
server.listen(port_listen_defalt);
public void onrequest(asynchttpserverrequest request, asynchttpserverresponse response) {
log.d(tag, "进来了,哈哈");
string uri = request.getpath();
//这个是获取header参数的地方,一定要谨记哦
multimap headers = request.getheaders().getmultimap();
if (checkuri(uri)) {// 针对的是接口的处理
//注意:这个地方是获取post请求的参数的地方,一定要谨记哦
multimap parms = (( asynchttprequestbody<multimap>)request.getbody()).get();
if (headers != null) {
logutil.d(tag, headers.tostring());
if (parms != null) {
logutil.d(tag, "parms = " + parms.tostring());
if (stringutil.isempty(uri)) {
throw new runtimeexception("无法获取请求地址");
if ("options".tolowercase().equals(request.getmethod().tolowercase())) {
logutil.d(tag, "options探测性请求");
addcorsheaders(status.request_ok, response);
return;
switch (uri) {
} else {
// 针对的是静态资源的处理
string filepath = getfilepath(uri); // 根据url获取文件路径
if (filepath == null) {
logutil.d(tag, "sd卡没有找到");
response.send("sd卡没有找到");
file file = new file(filepath);
if (file != null && file.exists()) {
log.d(tag, "file path = " + file.getabsolutepath());
response.sendfile(file);//和nanohttpd不一样的地方
log.d(tag, "file path = " + file.getabsolutepath() + "的资源不存在");
根据上面的例子,主要说以下几点:{大概说的就是api用法啊这一类的}
1)例如:server.addaction(“options”, “[\d\d]“, this)是通用的过滤请求的方法。第一个参数是请求的方法,例如用“options”、“delete”、“post”、“get”等(注意用大写),第二个参数是过滤uri的正则表达式,此处是过滤所有的uri,第三个是回调参数。server.post(“[\d\d]“, this)、server.get(“[\d\d]*”, this)这个是上一个方法的特例。server.listen(port_listen_defalt)这个是监听端口;
2) request.getheaders().getmultimap()
这个是获取header参数的地方,一定要谨记哦;
3)(( asynchttprequestbody<multimap>)request.getbody()).get()这个地方是获取post请求的参数的地方;
4)获取静态资源的代码是在回调方法onresponse的else中,例子如上。
5)说一下options的坑点,因为androidasync这个框架中封装的返回http的状态码只有两种,假如过滤方法中没有包含例如options的请求方法,实际上返回给客户端的http状态码是400,而反映到浏览器的报错信息竟然是跨域的问题,找了很久才找到,请注意。
总结:
1)同一个页面:
nanohttpd耗时:1.4s
androidasync耗时:1.4s
但是在第二次进去的时候,androidasync的耗时明显比第一个少了,笔者猜测是因为androidasync底层做了一些处理。
2)从api分析的话,nanohttpd的用法比较方便,获取传递的参数那些的api比较好用;androidasync的api就相对来说要复杂一些,例如params的获取。
3)从场景来分析的话,如果需要并发量高的需求,一定要用androidasync;但是如果不需要的话,那就再具体分析。
本文作者:佚名
来源:51cto