一、让浏览器获得文件路径
try {
File dir=new File(
CilentHandler.class.getClassLoader()
.getResource(".").toURI()
);
// 定位target/classes/static目录
File staticDir=new File(dir,"static");
二、要点
状态行,响应头,和HTML的文件头没关系,前面是不可见的。
三、向页面输出
1.获取请求(自己写可以)
private String method;//请求方式
private String uri;//抽象路径
private String protocol;//协议版本
1.1截取字符串:
private String readLine() throws IOException {
//当对同一个socket调用多次readline都是在调用同一个socket
InputStream is = socket.getInputStream();
int a;
StringBuilder builder = new StringBuilder();
char pre = 'a', cur = 'a';
while ((a = is.read()) != -1) {
cur = (char) a;
if (pre == 13 && cur == 10) {
break;
}
builder.append(cur);
pre = cur;
}
String str = builder.toString().trim();
return str;
}
1.2对截取到的字符串进行再次截取
//解析消息请求行
private void parseRequestLine() throws IOException {
String str = readLine();
//split会将字符串按“ ”空格拆分
String[] data = str.split(" ");
method = data[0];
uri = data[1];
protocol = data[2];
System.out.println(method + " , " + uri + " , " + protocol);
}
1.3 这里有误区,每一次调用readline都是对同一个stock操作,每次截取读取都会往后走,如同read();方法一样。
//解析请求消息头
private void paresHeaders() throws IOException {
while (true) {
String str = readLine();
if (str.isEmpty()) {
break;
}//存消息头
String[] data1 = str.split(": ");
headers.put(data1[0], data1[1]);
headers.forEach((k,v)-> System.out.println(k+","+v));
}
}
2.对浏览器进行响应
2.1获取路径(此方法为固定格式,只需修改类名就行)
try {
File dir=new File(
CilentHandler.class.getClassLoader()
.getResource(".").toURI()
);
// 定位target/classes/static目录
File staticDir=new File(dir,"static");
2.2对路径进行拼接(path为获取浏览器传输过来的URI)
String path = request.getUri();
System.out.println("请求的路径为 : " + path);
// 返回path的.html
File file = new File(staticDir, path);
2.3反馈浏览器就是向浏览器的页面进行字节输出
file指的就是获取过来的地址值。读取HTML文件再写到浏览器上。
FileInputStream fos = new FileInputStream(file);
byte[] bytes = new byte[1024 * 10];
int len;
while ((len = fos.read(bytes)) != -1) {
os.write(bytes);
}
2.4在写到浏览器上时需要将消息头补充完整
对流的输出封装
line = "HTTP/1.1 200 OK";
println("line");
line = "Content-Type: text/html";
println("line");
line = "Content-Length: " + file.length();
println("line");
//以换行,回车结尾
os.write(13);
os.write(10);
public void println(String line) throws IOException {
OutputStream os = socket.getOutputStream();
byte[] buf = line.getBytes(StandardCharsets.ISO_8859_1);
os.write(buf);
os.write(13);
os.write(10);
}