上回咱们把基本的架子搭好了,不过也说了这个架子基本是不可用的,这回咱们就把它改造成基本可用的。
3. 支持html文件
首先我们先实现对html的支持:
- 添加src/main/assets文件夹,把html文件都放到这个文件夹下
- 修改server函数:
public Response serve(IHTTPSession session) {
String uri = session.getUri();
String filename = uri.substring(1);
if (uri.equals("/"))
filename = "index.html";
String response = "";
String line = "";
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(_mainContext.getAssets().open(filename)));
while ((line = reader.readLine()) != null) {
response += line;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return newFixedLengthResponse(response);
}
P.S.: 留个作业,为啥这里选assets文件夹呢?其他文件夹可以吗?
其实逻辑很简单,就是找到想要打开的网页文件,然后把文件内容读出来返回。
看上去这个逻辑应该也能应付js和css对吧(image咱后面再说),但实际上你添加上js文件后,你会发现浏览器端是访问不到的,为啥呢?
这个咱得去nanoHTTPD的源码里瞅瞅去。(别一说要看源码就慌了,没那么恐怖,咱只看跟咱们问题相关的那几行,然后再结合上猜就差不多了)
4. 浅入探索nanoHTTPD源码
这里咱们用到一个newFixedLengthResponse函数,所以咱们首先看看这个函数是咋干活的:
public static Response newFixedLengthResponse(String msg) {
return newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_HTML, msg);
}
就一行代码,简单明了,一个html的状态,一个html的类型,一个咱刚刚传入的html正文。再结合咱的js和css,应该能猜出问题出在MIME_HTML上,我们看下这个变量的定义:
public static final String MIME_HTML = "text/html";
如果你对html比较在行的话,应该能猜出来js对应的这个值应该是:text/javascript,css对应的是:text/css对吧,实际上在nanoHTTPD项目的源码里也确实有这个定义的:
#default mime types for nanohttpd, use META-INF/mimetypes.properties for user defined mimetypes
css=text/css
htm=text/html
html=text/html
xml=text/xml
java=text/x-java-source, text/java
md=text/plain
txt=text/plain
asc=text/plain
gif=image/gif
jpg=image/jpeg
jpeg=image/jpeg
png=image/png
svg=image/svg+xml
mp3=audio/mpeg
m3u=audio/mpeg-url
mp4=video/mp4
ogv=video/ogg
flv=video/x-flv
mov=video/quicktime
swf=application/x-shockwave-flash
js=application/javascript
pdf=application/pdf
doc=application/msword
ogg=application/x-ogg
zip=application/octet-stream
exe=application/octet-stream
class=application/octet-stream
m3u8=application/vnd.apple.mpegurl
ts=video/mp2t
5. 支持js和css
本着代码能工作,绝不多学一点”的原则,我们再改下咱们的代码:
public Response serve(IHTTPSession session) {
String uri = session.getUri();
System.out.println("####MyWebServer:" + uri);
String filename = uri.substring(1);
if (uri.equals("/"))
filename = "index.html";
String mimetype = "text/html";
if (filename.contains(".html") || filename.contains(".htm")) {
mimetype = "text/html";
} else if (filename.contains(".js")) {
mimetype = "text/javascript";
} else if (filename.contains(".css")) {
mimetype = "text/css";
} else {
filename = "index.html";
mimetype = "text/html";
}
String response = "";
String line = "";
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(_mainContext.getAssets().open(filename)));
while ((line = reader.readLine()) != null) {
response += line;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return newFixedLengthResponse(Response.Status.OK, mimetype, response);
}
OK,app重启,浏览刷新!
是不是js和css也都OK了。(不OK的同学,下课可以找我)
嗯,就剩下一个image显示的问题了,咱一篇见。