forked from softeerbootcamp-7th/be-was
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpRequest.java
More file actions
102 lines (82 loc) · 2.72 KB
/
HttpRequest.java
File metadata and controls
102 lines (82 loc) · 2.72 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
97
98
99
100
101
102
package webserver.http.request;
import webserver.http.HttpMethod;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpRequest {
private final HttpMethod method;
private final Map<String, String> headers;
private final URI uri;
private String httpVersion;
private String contentType;
private Map<String, String> queryMap;
private byte[] body;
private InetSocketAddress requestAddress;
public String getHeader(String key){
return headers.get(key.toLowerCase());
}
public void setHeader(String key, String value){
headers.put(key.toLowerCase(), value);
}
public List<String> getHeaders(){
return headers.keySet().stream().toList();
}
public String getPath(){
return uri.getPath();
}
public String getQuery(){
return uri.getQuery();
}
public String getQueryValue(String key){
if (queryMap == null) {
queryMap = parseQueryToMap(uri.getQuery());
}
return queryMap.get(key);
}
public HttpMethod getMethod(){
return this.method;
}
private HttpRequest (HttpMethod method,
String target,
String httpVersion) {
this.method = method;
this.uri = URI.create(target);
this.httpVersion = httpVersion;
this.headers = new HashMap<>();
}
public static HttpRequest from(String requestLine){
String[] parts = requestLine.split(" ");
return new HttpRequest(
HttpMethod.valueOf(parts[0].strip().toUpperCase()),
parts[1].strip(),
parts[2].strip());
}
private static Map<String, String> parseQueryToMap(String queryString) {
Map<String, String> map = new HashMap<>();
if (queryString == null || queryString.isBlank()) {
return map;
}
String[] pairs = queryString.strip().split("&");
for (String pair : pairs) {
if (pair.isEmpty()) continue;
String[] kv = pair.split("=", 2); // value에 '=' 들어가도 OK
String rawKey = kv[0];
String rawValue = kv.length == 2 ? kv[1] : "";
String key = urlDecode(rawKey);
String value = urlDecode(rawValue);
map.put(key, value);
}
return map;
}
private static String urlDecode(String s) {
try {
return URLDecoder.decode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 not supported", e);
}
}
}