【发布时间】:2016-07-08 10:12:01
【问题描述】:
我正在尝试使用 com.sun.net.httpserver 类编写一个简单的 http 服务器。我在启动时将 html 文件 (index.html) 发送到浏览器,但我不知道如何包含外部 css 文件。当 css 代码放在 html 文件中时,它可以工作。我知道,该浏览器应该发送一个请求,向服务器询问 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();
}
【问题讨论】:
-
这行代码是做什么的
server.createContext("/", new indexHandler());? -
它创建一个与路径“/”关联的http上下文。该路径的所有请求都由 indexHandler 对象处理。
-
如果你想写一个HTTP服务器,你需要了解一个HTTP请求和它的响应之间的关系。告诉你这相当于一个教程。
-
@bizkhit 对,你应该怎么做才能接受另一条路? (你的情况是css)
-
创建新上下文?但我不知道这条路应该是什么样子。假设我在 C:\MyApp\src\com\xyz\view\style.css 中有我的 css 文件。我应该给出 createContext 方法的完整路径吗?
标签: java html css httpserver simplehttpserver