-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpResponse.java
More file actions
51 lines (43 loc) · 1.44 KB
/
Copy pathHttpResponse.java
File metadata and controls
51 lines (43 loc) · 1.44 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
package was.httpserver;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import static java.nio.charset.StandardCharsets.UTF_8;
public class HttpResponse {
private final PrintWriter writer;
private int statusCode = 200;
private final StringBuilder bodyBuilder = new StringBuilder();
private String contentType = "text/html; charset=UTF-8";
public HttpResponse(PrintWriter writer) {
this.writer = writer;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public void writeBody(String body){
bodyBuilder.append(body);
}
public void flush(){
int contentLength = bodyBuilder.toString().getBytes(UTF_8).length;
writer.println("HTTP/1.1 " + statusCode + " " + getResponsePharse(statusCode));
writer.println("Content-Type: " + contentType);
writer.println("Content-Length: " + contentLength);
writer.println();
writer.println(bodyBuilder);
writer.flush();
}
private String getResponsePharse(int statusCode){
switch (statusCode){
case 200:
return "OK";
case 404:
return "Not Found";
case 500:
return "Internal Server Error";
default:
return "Unknow Status";
}
}
}