-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathHttpRequest.java
More file actions
99 lines (78 loc) · 2.53 KB
/
HttpRequest.java
File metadata and controls
99 lines (78 loc) · 2.53 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
package http;
import util.HttpRequestUtils;
import util.IOUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class HttpRequest {
private String url;
private HttpMethod method;
private String protocol;
private Map<String, String> headers = new HashMap<>();
private Map<String, String> cookies = null;
private Map<String, String> data;
private String body;
private HttpRequest() {
}
public String getUrl() {
return url;
}
public static HttpRequest of(InputStream in) throws IOException {
HttpRequest httpRequest = new HttpRequest();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String buffer;
buffer = br.readLine();
httpRequest.addStartLine(buffer);
while (!(buffer = br.readLine()).equals("")) {
httpRequest.addHeaders(buffer);
}
String contentLength = httpRequest.header("Content-Length");
if (contentLength != null) {
httpRequest.addBody(IOUtils.readData(br, Integer.parseInt(contentLength)));
}
return httpRequest;
}
private void addStartLine(String buffer) {
String[] startLine = buffer.split(" ");
method = HttpMethod.valueOf(startLine[0].toUpperCase());
url = startLine[1];
protocol = startLine[2];
String[] target = startLine[1].split("\\?");
url = target[0];
if (target.length > 1 && method == HttpMethod.GET) {
data = HttpRequestUtils.parseQueryString(target[1]);
}
}
private void addHeaders(String buffer) {
HttpRequestUtils.Pair pair = HttpRequestUtils.parseHeader(buffer);
headers.put(pair.getKey(), pair.getValue());
String cookies;
if ((cookies = headers.get("Cookie")) != null) {
this.cookies = HttpRequestUtils.parseCookies(cookies);
}
}
private void addBody(String readData) {
body = readData;
if (method == HttpMethod.POST) {
data = HttpRequestUtils.parseQueryString(readData);
}
}
public String header(String key) {
return headers.get(key);
}
public String cookie(String key) {
if (cookies == null) {
return null;
}
return cookies.get(key);
}
public HttpMethod method() {
return method;
}
public String data(String key) {
return data.get(key);
}
}