-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyHttpServer.java
More file actions
46 lines (40 loc) · 1.4 KB
/
MyHttpServer.java
File metadata and controls
46 lines (40 loc) · 1.4 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
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Arrays;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Main {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/main", new MyHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String cookieValue = t.getRequestHeaders().getFirst("Cookie");
int visitCount = 0;
try {
visitCount = Arrays.asList(cookieValue.split(";"))
.stream()
.filter(s -> s.trim().startsWith("visitCount"))
.mapToInt(s -> Integer.valueOf(s.split("=")[1]))
.max()
.orElse(0);
System.out.printf("Visit Count: %d\n", visitCount);
}
catch (Exception e) {
visitCount = 0;
}
String response = "<html><body><p>Your visit count:</p><h1>" + visitCount + "<h1></body></html>";
t.getResponseHeaders().add("Set-Cookie", "visitCount=" + Integer.toString(visitCount+1));
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}