关于Andriod 调用nanohttpd类实现局域网访问html

    想把工做中遇到的问题记录下来,刚刚学会调用nanohttpd类,简洁明了。附上nanohttpd包下载地址https://github.com/NanoHttpd/nanohttpd html

首先介绍一下nanohttpd在此处的用途,能够经过此类搭建一个轻量级的Web服务器,实现功能须要链接同一个局域网,PC端访问Andriod设备链接局域网的地址时能打开目录下的html文件。上干货:git

一、确定是先启动线程,github

 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     }

二、Web服务器没有端口号怎么行,在此我设置的默认端口号是8080web

public SimpleServer() { super(8080); }

三、至此就进入数据处理函数。想要打开文件就必须先索引到该文件的目录服务器

 @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); } }

 

 

 

四、经过索引文件名,把html文件转为文本模式session

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(); }

五、以流的形式向服务端发送app

public Response(IStatus status, String msg, InputStream data, int i) { this(Status.OK, MIME_HTML, msg); }

六、关闭线程ide

 @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;但愿也能帮助到你们。函数

相关文章
相关标签/搜索