想把工作中遇到的問題記錄下來,剛剛學會調用nanohttpd類,簡潔明瞭。附上nanohttpd包下載地址https://github.com/NanoHttpd/nanohttpd 首先介紹一下nanohttpd在此處的用途,可以通過此類搭建一個輕量級的Web伺服器,實現功能需要連接同一個區域網, ...
想把工作中遇到的問題記錄下來,剛剛學會調用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;希望也能幫助到大家。