我写了一个简单的Web服务器。 当我访问不存在的资源时,我会收到正确的服务器响应 但是当我访问现有资源(index.xml)时,服务器无法响应
以下是我的服务器用来发送请求的代码
public class Response {
public static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output) {
this.output = output;
}
public void setRequest(Request request) {
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if(file.exists()){
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1){
output.write(bytes,0,ch);
ch = fis.read(bytes,0,BUFFER_SIZE);
}
}else {
String errorMessage = "HTTP/1.1 404 File Not Found\r\n"+
"Content-type: text/html\r\n"+
"Content-length: 23\r\n"+"" +
"\r\n"+
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
} catch (Exception e) {
System.out.println(e.toString());
}finally {
if(fis!=null){
fis.close();
}
}
}
}