我使用 sun.net.HttpServer 实现了自己的小型 Web 服务器...以启用 css 和 javascript 我使用 HttpHandler 编写代码,但是 js 目录有两个文件...它适用于一个文件,但是当两个文件要传输时...发生了错误。喜欢
java.io.IOException:标头已发送
如何解决这个问题......这里是编码
class DirectoryServicesForJS implements HttpHandler {
@Override
public void handle(HttpExchange http) throws IOException {
// HTTP METHOD (GET, POST, DELETE, PUT)
System.out.println("Java script transfered...");
List<String> jsFiles = new ArrayList<String>();
;
Files.walk(Paths.get("web/js")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
jsFiles.add(filePath.toString());
}
});
for (String filePath : jsFiles) {
try {
StringBuilder code = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader(
filePath));
String str;
while ((str = in.readLine()) != null) {
code.append(str);
}
in.close();
} catch (IOException e) {
System.out.println();
}
String response = code.toString();
http.sendResponseHeaders(200, response.length()); // error line
System.out.println(filePath);
http.setAttribute("Content-Type", "text/javascript");
OutputStream os = http.getResponseBody();
os.write(response.getBytes());
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}