如何修复java sun.net.Httpserver标头已发送错误?
我正在使用sun.net.HttpServer实现自己的微型web服务器。。。为了启用css和javascript,我使用HttpHandler编写了代码,但是js目录有两个文件…它只适用于一个文件,但是当需要传输两个文件时。。。发生错误。像 java.io.IOException:已发送头文件 如何解决这个问题。。。这里是编码如何修复java sun.net.Httpserver标头已发送错误?,java,servlets,com.sun.net.httpserver,Java,Servlets,Com.sun.net.httpserver,我正在使用sun.net.HttpServer实现自己的微型web服务器。。。为了启用css和javascript,我使用HttpHandler编写了代码,但是js目录有两个文件…它只适用于一个文件,但是当需要传输两个文件时。。。发生错误。像 java.io.IOException:已发送头文件 如何解决这个问题。。。这里是编码 class DirectoryServicesForJS implements HttpHandler { @Override public void
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();
}
}
}
}
类DirectoryServicesForJS实现HttpHandler{
@凌驾
公共无效句柄(HttpExchangeHTTP)引发IOException{
//HTTP方法(GET、POST、DELETE、PUT)
println(“Java脚本传输…”);
List jsFiles=new ArrayList();
;
Files.walk(path.get(“web/js”)).forEach(filePath->{
if(Files.isRegularFile(filePath)){
add(filePath.toString());
}
});
for(字符串文件路径:jsFiles){
试一试{
StringBuilder代码=新的StringBuilder();
试一试{
BufferedReader in=新的BufferedReader(新文件读取器(
文件路径);
字符串str;
而((str=in.readLine())!=null){
代码追加(str);
}
in.close();
}捕获(IOE异常){
System.out.println();
}
字符串响应=code.toString();
http.sendResponseHeaders(200,response.length());//错误行
System.out.println(文件路径);
setAttribute(“内容类型”、“文本/javascript”);
OutputStream os=http.getResponseBy();
write(response.getBytes());
os.close();
}捕获(例外情况除外){
例如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();
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">×</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>
购物门户
&时代;
成功您是新用户。
欢迎来到购物门户网站
内容将在稍后更新
您似乎试图为一个请求发送多个文件。HTTP不是这样工作的。如果客户端请求/index.html
,则发送该文件的内容,而不发送其他内容。移除你的for循环,它不会工作。好的,兄弟。如果我像这样改变<代码>列表jsFiles=newarraylist();Files.walk(path.get(“web/js”)).forEach(filePath->{if(Files.isRegularFile(filePath)){jsFiles.add(filePath.getFileName().toString());}});对于(String jsFile:jsFiles){System.out.println(jsFile);server.createContext(“/js/”+jsFile,new DirectoryServicesForJS(jsFile));}也只调用一次。。。我该怎么办?修复并获得解决方案。我应该在哪里应用多线程,HttpHandler或HttpServer?对于单个请求,您需要使用单个文件进行响应。您的代码甚至不关心请求是针对哪个文件的(或者它是否是GET
请求)。检查HttpExchange
以查看请求的内容,然后返回该文件。即使多线程也无法工作<代码>for(String jsFile:jsFiles){System.out.println(jsFile);新线程(new Runnable(){public void run(){server.createContext(“/js/”+jsFile,new DirectoryServicesForJS(jsFile));}).start();}我该怎么办?如何获得解决方案。。。回复我@Kayaman