-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpResponse.java
More file actions
96 lines (76 loc) · 2.68 KB
/
Copy pathHttpResponse.java
File metadata and controls
96 lines (76 loc) · 2.68 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package httpserver;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
public abstract class HttpResponse {
protected static SimpleDateFormat rfc1123Format;
static {
rfc1123Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'");
rfc1123Format.setTimeZone(TimeZone.getTimeZone("UTC"));
}
protected HttpStatus status;
protected HashMap<String, String> headers;
protected HttpRequest request;
protected boolean persistent;
private void setPersistentFlag() {
String connectionRequest = request.getHeader("Connection");
persistent = connectionRequest == null ||
connectionRequest.toLowerCase().equals("keep-alive");
}
public HttpResponse() {
this(new HttpRequest());
}
public HttpResponse(HttpRequest httpRequest) {
this(HttpStatus.OK(), httpRequest);
}
public HttpResponse(HttpStatus responseStatus, HttpRequest httpRequest) {
status = responseStatus;
headers = new HashMap<String, String>();
request = httpRequest;
setPersistentFlag();
}
public String toString() {
return status.toResponseBody();
}
public void setHeader(String headerName, String headerValue) {
headers.put(headerName.toLowerCase(), headerValue.trim());
}
public boolean hasBody() {
return !(
status.equals(HttpStatus.NoContent()) ||
status.equals(HttpStatus.NotModified()) ||
request.getMethod() == HttpRequest.Method.HEAD);
}
protected void addRequiredHeaders() {
Date now = new Date(System.currentTimeMillis());
setHeader("Date", rfc1123Format.format(now));
if (!persistent) {
setHeader("Connection", "close");
} else {
setHeader("Keep-Alive", String.format("timeout=%1d", HttpServer.DEFAULT_TIMEOUT));
}
}
public boolean isPersistent() {
return persistent;
}
public void write(OutputStream out) throws IOException {
// Finalize Reponse
addRequiredHeaders();
PrintWriter writer = new PrintWriter(out, true);
writer.println(status.toResponseLine());
for (Map.Entry<String, String> header: headers.entrySet()) {
writer.println(String.format("%1s: %2s", header.getKey(), header.getValue()));
}
writer.println("");
writer.flush();
if (hasBody()) {
writeBody(out);
}
}
public abstract void writeBody(OutputStream out) throws IOException;
}