-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpResponse.java
More file actions
65 lines (53 loc) · 1.54 KB
/
HttpResponse.java
File metadata and controls
65 lines (53 loc) · 1.54 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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpResponse {
private Map<String, String> headers;
private String body = null;
private int status;
public HttpResponse() {
this.headers = new HashMap<>();
}
public HttpResponse(int status, String body) {
this.status = status;
this.headers = new HashMap<>();
this.headers.put("Content-Type", "text/plain");
this.headers.put("Content-Length", String.valueOf(body.getBytes().length));
this.body = body;
}
private String buildResponseLine() {
return "HTTP/1.1 " + status + " OK\r\n";
}
public void setStatus(int status) {
this.status = status;
}
public void setBody(String body) {
this.body = body;
this.headers.put("Content-Type", "text/plain");
this.headers.put("Content-Length", String.valueOf(body.getBytes().length));
}
public String toString() {
return buildResponseLine() + stringifyHeaders() + body;
}
private String stringifyHeaders() {
List<String> headerString = new ArrayList<>();
headers.forEach((key, value) -> {
if (value.isEmpty()) {
headerString.add(key + "\r\n");
} else {
headerString.add(key + ": " + value + "\r\n");
}
});
headerString.add("\r\n");
return String.join("", headerString);
}
public HttpResponse setHeader(String key, String value) {
headers.put(key, value);
return this;
}
public HttpResponse setHeader(String key) {
headers.put(key, "");
return this;
}
}