想把工作中遇到的问题记录下来,刚刚学会调用nanohttpd类,简洁明了。附上nanohttpd包下载地址https://github.com/NanoHttpd/nanohttpd
首先介绍一下nanohttpd在此处的用途,可以通过此类搭建一个轻量级的Web服务器,实现功能需要连接同一个局域网,PC端访问Andriod设备连接局域网的地址时能打开目录下的html文件。上干货:
1、肯定是先启动线程,
1 public class MainActivity extends Activity {
2 private SimpleServer server;
3 @Override
4 protected void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6 super.onCreate(savedInstanceState);
7 server = new SimpleServer();
8 try {
9 server.start();
10 Log.i("Httpd",Server startup);
11 } catch(IOException ioe) {
12 Log.w("Httpd",server startup failed);
13 }
14 }
2、Web服务器没有端口号怎么行,在此我设置的默认端口号是8080
public SimpleServer() {
super(8080);
}
3、至此就进入数据处理函数。想要打开文件就必须先索引到该文件的目录
@Override
public Response serve(IHTTPSession session) {
LogTools.d(TAG, "OnRequest:" + session.getUri());
String uri = session.getUri();//索引文件名
String pathname = path + uri;
LogTools.d(TAG, path + uri);
return FileStream(session,pathname);
}
public Response FileStream(IHTTPSession session, String pathname) {
try {
FileInputStream fis = new FileInputStream(pathname);
LogTools.d(TAG, pathname);
return Response.newChunkedResponse(Status.OK,readHtml(pathname),fis);
} catch (FileNotFoundException e){
e.printStackTrace();
return response404(session,pathname);
}
}
4、通过索引文件名,把html文件转为文本模式
private String readHtml(String pathname) {
BufferedReader br=null;
StringBuffer sb = new StringBuffer();
try {
br=new BufferedReader(new InputStreamReader(new FileInputStream(pathname), "UTF-8"));
String temp=null;
while((temp=br.readLine())!=null){
sb.append(temp);
}
} catch (FileNotFoundException e) {
LogTools.e(TAG, "Missing operating system!");
e.printStackTrace();
} catch (IOException e) {
LogTools.e(TAG, "write error!");
e.printStackTrace();
}
LogTools.d(TAG, sb.toString());
return sb.toString();
}
5、以流的形式向服务端发送
public Response(IStatus status, String msg, InputStream data, int i) {
this(Status.OK, MIME_HTML, msg);
}
6、关闭线程
@Override
protected void onDestroy() {
super.onDestroy();
if (server != null){
server.stop();
}
Log.w("Httpd", "The server stopped.");
}
例如我在IE上输入192.168.4.101:8080/index.html 我就能打开Andriod目录下/mnt/sdcard/webView/index.html;希望也能帮助到大家。

