-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpRequest.java
More file actions
80 lines (67 loc) · 1.95 KB
/
HttpRequest.java
File metadata and controls
80 lines (67 loc) · 1.95 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
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HttpRequest {
private String path;
private HttpMethod method;
private Map<String, String> headers;
private String body;
public HttpRequest(BufferedReader reader) throws IOException {
this.headers = new HashMap<String, String>();
extractMethodAndPath(reader.readLine());
extractHeaders(reader);
extractBody(reader);
}
public Map<String, String> headers() {
return this.headers;
}
public String body() {
return body;
}
public String path() {
return path;
}
public HttpMethod method() {
return method;
}
public String toString() {
return "Path: " + path + "\n" +
"Method: " + method + "\n" +
"Headers: " + headers.values() + "\n" +
"Body: " + body + "\n";
}
private void extractMethodAndPath(String httpRequestLine) throws IOException {
String[] methodPath = httpRequestLine.split(" ");
this.method = HttpMethod.valueOf(methodPath[0]);
this.path = methodPath[1];
}
private void extractBody(BufferedReader reader) throws IOException {
String cl = headers.get("content-length");
if (cl == null) {
body = null;
return;
}
int contentLength = Integer.parseInt(cl);
char[] cbuf = new char[contentLength];
reader.read(cbuf, 0, contentLength);
body = String.valueOf(cbuf);
}
private void extractHeaders(BufferedReader reader) throws IOException {
String line = reader.readLine();
while (line != null && !line.isEmpty()) {
int idx = line.indexOf(":");
String key = "";
String value = "";
if (idx == -1) {
key = line.toLowerCase().trim();
headers.put(key, value);
} else {
key = line.substring(0, idx).toLowerCase().trim();
value = line.substring(idx + 1).trim();
headers.put(key, value);
}
line = reader.readLine();
}
}
}