關於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;但願也能幫助到你們。函數

相關文章
相關標籤/搜索