I implementing own tiny web server using sun.net.HttpServer... to enable css and javascript i wrote code using HttpHandler, but js directory having two files...it's working for one file, but when two files to transfer... error occurred. like
java.io.IOException: headers already sent
How to fix this... here is coding
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();
}
}
}
}