-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathResponse.java
More file actions
82 lines (74 loc) · 1.74 KB
/
Response.java
File metadata and controls
82 lines (74 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.hjy.response;
import java.io.*;
import java.net.Socket;
import com.hjy.request.Request;
public class Response {
private Socket client;
private PrintStream ps;
private String path = null;
public Response() {
}
public Response(Socket client) {
super();
this.client = client;
try {
ps = new PrintStream(client.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void forward() throws FileNotFoundException {
// 响应(把服务器上有的资源用流传给客户端)
InputStream fis = null;
try {
fis = this.getClass().getClassLoader().getResourceAsStream(path);
ps.println("HTTP/1.1 200 OK");
ps.println();
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
ps.write(buf, 0, len);
ps.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (ps != null) {
ps.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void forward(String url) {
/*
* url处理分3种情况 1.为空:返回默认资源 2.不空存在,返回该资源 3.不空不存在,返回错误信息
*/
if (url.equals("/")) {
path = "html/2.jpg";
} else {
path = "html" + url;
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
if (inputStream == null) {
path = "html/error.html";
}
}
try {
forward();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}