如何修复java sun.net.Httpserver标头已发送错误



我使用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();
            }
        }
    }
}

要传输所有css和js,我们可以这样编写代码。。。

        server = HttpServer.create(new InetSocketAddress(port), backlog);
        server.createContext("/", new IndexPage());
        List<String> cssFiles = new ArrayList<String>();
        Files.walk(Paths.get("web/css")).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                cssFiles.add(filePath.getFileName().toString());
            }
        });
        for (String cssFile : cssFiles) {
            server.createContext("/css/" + cssFile,
                    new DirectoryServicesForCSS(cssFile));
        }
        List<String> jsFiles = new ArrayList<String>();
        Files.walk(Paths.get("web/js")).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                jsFiles.add(filePath.getFileName().toString());
            }
        });
        for (String jsFile : jsFiles) {
            server.createContext("/js/" + jsFile,
                    new DirectoryServicesForJS(jsFile));
        }
        // server.setExecutor(Executors.newCachedThreadPool());
        server.setExecutor(null);
        server.start();

我们应该像这样编写HttpHandler代码。。。

    class DirectoryServicesForCSS implements HttpHandler {
    private String style;
    public DirectoryServicesForCSS(String style) {
        this.style = style;
    }
    @Override
    public void handle(HttpExchange http) throws IOException {
        // HTTP METHOD (GET, POST, DELETE, PUT)
        if (http.getRequestMethod().equals("GET")) {
            System.out.println("cascade style sheet transfered..." + style);
            try {
                StringBuilder contentBuilder = new StringBuilder();
                try {
                    BufferedReader in = new BufferedReader(new FileReader(
                            "web/css/" + style));
                    String str;
                    while ((str = in.readLine()) != null) {
                        contentBuilder.append(str);
                    }
                    in.close();
                } catch (IOException e) {
                }
                String response = contentBuilder.toString();
                http.sendResponseHeaders(200, response.length());
                OutputStream os = http.getResponseBody();
                os.write(response.getBytes());
                os.flush();
                os.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
     class DirectoryServicesForJS implements HttpHandler {
    private String script;
    public DirectoryServicesForJS(String script) {
        this.script = script;
    }
    @Override
    public void handle(HttpExchange http) throws IOException {
        // HTTP METHOD (GET, POST, DELETE, PUT)
        if (http.getRequestMethod().equals("GET")) {
            System.out.println("Java scripts transfered..." + script);
            try {
                StringBuilder code = new StringBuilder();
                try {
                    BufferedReader in = new BufferedReader(new FileReader(
                            "web/js/" + script));
                    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());
                http.setAttribute("Content-Type", "text/javascript");
                OutputStream os = http.getResponseBody();
                os.write(response.getBytes());
                os.flush();
                os.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

并确保它在我们的html页面中可用。。

<html>
<head>
    <title>Shopping Portal</title>
    <link href="css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body class="container-fluid">
<div class="alert alert-success alert-dismissable">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <strong>Successfully!</strong> You are new user.
</div>
    <h1 class="text-primary">Welcome to Shopping Portal</h1>
    <hr/>
    <p>Content will be updated later</p>
</body>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</html>

最新更新