2013-08-03 39 views
2

在index.html中,使用了外部CSS,並使用圖像src的路徑來請求文件夾中的css圖像。然而,圖像不加載和CSS樣式不適用於頁面。如何從Nanohttpd提供外部css,jpg和gif文件(Nanohttpd在普通PC上運行,不在Android上)?

import java.io.*; 
import java.util.*; 

/** 
* An example of subclassing NanoHTTPD to make a custom HTTP server. 
*/ 
public class HelloServer extends NanoHTTPD 
{ 
    public HelloServer() throws IOException 
    { 
     super(8080, new File(".")); 
    } 

    public Response serve(String uri, String method, Properties header, Properties parms, Properties files) { 

     BufferedReader br = null; 
     String msg=""; 

     try { 

      String sCurrentLine; 

      br = new BufferedReader(new FileReader("index.html")); 

      while ((sCurrentLine = br.readLine()) != null) { 
       //System.out.println(sCurrentLine); 
       msg = msg + sCurrentLine; 
       System.out.println(sCurrentLine); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (br != null)br.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 
     return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, msg); 
    } 


    public static void main(String[] args) 
    { 
     try 
     { 
      new HelloServer(); 
     } 
     catch(IOException ioe) 
     { 
      System.err.println("Couldn't start server:\n" + ioe); 
      System.exit(-1); 
     } 
     System.out.println("Listening on port 8080. Hit Enter to stop.\n"); 
     try { System.in.read(); } catch(Throwable t) {}; 
    } 
} 

index.html中,外部CSS被使用和到圖片src路徑用於從一個文件夾請求圖像,但。然而,圖像不加載和CSS樣式不適用於頁面。

回答

1

一旦你發回HTML文件,瀏覽器將會運行,然後對其他資源的後續請求 - 圖像,JS文件,CSS等。你需要做的是看「uri」參數和它會告訴你哪個文件需要發送回客戶端。而不是對「index.html」進行硬編碼,您將需要將文件名取消所請求的內容。