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

时间:2015-03-05 09:15:55

标签: java servlets com.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();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

传输所有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>