2016-03-21 98 views
1

我想寫一個簡單的http服務器,使用com.sun.net.httpserver類。我在啓動時向瀏覽器發送html文件(index.html),但我不知道如何包含外部css文件。它工作時,CSS代碼放在HTML文件。我知道,該瀏覽器應發送請求,要求服務器的css文件,但我不知道如何接收此請求並將此文件發送回瀏覽器。如果可能會有所幫助,我會在下面附上我的代碼片段。如何使用com.sun.net.httpserver包含css文件?

private void startServer() 
{ 
    try 
    { 
     server = HttpServer.create(new InetSocketAddress(8000), 0); 
    } 
    catch (IOException e) 
    { 
     System.err.println("Exception in class : " + e.getMessage()); 
    } 
    server.createContext("/", new indexHandler()); 
    server.setExecutor(null); 
    server.start(); 
} 

private static class indexHandler implements HttpHandler 
{ 
    public void handle(HttpExchange httpExchange) throws IOException 
    { 
     Headers header = httpExchange.getResponseHeaders(); 
     header.add("Content-Type", "text/html"); 
     sendIndexFile(httpExchange);    
    } 
} 

static private void sendIndexFile(HttpExchange httpExchange) throws IOException 
{ 
    File indexFile = new File(getIndexFilePath()); 
    byte [] indexFileByteArray = new byte[(int)indexFile.length()]; 

    BufferedInputStream requestStream = new BufferedInputStream(new FileInputStream(indexFile)); 
    requestStream.read(indexFileByteArray, 0, indexFileByteArray.length); 

    httpExchange.sendResponseHeaders(200, indexFile.length()); 
    OutputStream responseStream = httpExchange.getResponseBody(); 
    responseStream.write(indexFileByteArray, 0, indexFileByteArray.length); 
    responseStream.close(); 
} 
+0

這行代碼做了什麼'server.createContext(「/」,new indexHandler());'? –

+0

它創建一個與路徑「/」關聯的http上下文。此路徑的所有請求都由indexHandler對象處理。 – bizkhit

+0

如果要編寫HTTP服務器,則需要了解HTTP請求與其響應之間的關係。告訴你這將相當於一個教程。 – Raedwald

回答

0

沒有用於處理靜態內容的內置方法。你有兩個選擇。

要麼使用像nginx這樣的靜態內容的輕量級網絡服務器,但比分配應用程序更困難。

或創建您自己的文件服務類。爲此,您必須在您的Web服務器中創建一個新的上下文:

int port = 8080; 
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); 
// ... more server contexts 
server.createContext("/static", new StaticFileServer()); 

而不是創建將用於您的靜態文件的類。

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.OutputStream; 

import com.sun.net.httpserver.HttpExchange; 
import com.sun.net.httpserver.HttpHandler; 

@SuppressWarnings("restriction") 
public class StaticFileServer implements HttpHandler { 

    @Override 
    public void handle(HttpExchange exchange) throws IOException { 
     String fileId = exchange.getRequestURI().getPath(); 
     File file = getFile(fileId); 
     if (file == null) { 
      String response = "Error 404 File not found."; 
      exchange.sendResponseHeaders(404, response.length()); 
      OutputStream output = exchange.getResponseBody(); 
      output.write(response.getBytes()); 
      output.flush(); 
      output.close(); 
     } else { 
      exchange.sendResponseHeaders(200, 0); 
      OutputStream output = exchange.getResponseBody(); 
      FileInputStream fs = new FileInputStream(file); 
      final byte[] buffer = new byte[0x10000]; 
      int count = 0; 
      while ((count = fs.read(buffer)) >= 0) { 
       output.write(buffer, 0, count); 
      } 
      output.flush(); 
      output.close(); 
      fs.close(); 
     } 
    } 

    private File getFile(String fileId) { 
     // TODO retrieve the file associated with the id 
     return null; 
    } 
} 

對於getFile(String fileId)方法;您可以實現任何檢索與fileId關聯的文件的方式。一個不錯的選擇是創建鏡像URL層次結構的文件結構。如果你沒有很多文件,你可以使用HashMap來存儲有效的id文件對。