diff options
author | JJ | 2023-03-22 01:16:05 +0000 |
---|---|---|
committer | JJ | 2023-03-22 01:16:05 +0000 |
commit | d3a72b541b13d83d0a5562289c04fb951f3e367d (patch) | |
tree | e45c23569860d0c31e15582dc7504ef2209782d8 /src/main/model/http/HttpResponse.java | |
parent | f575e555b40629770dcec41eb1ec2f46cc645566 (diff) |
Initial skeleton of support for HTTP
Diffstat (limited to 'src/main/model/http/HttpResponse.java')
-rw-r--r-- | src/main/model/http/HttpResponse.java | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/main/model/http/HttpResponse.java b/src/main/model/http/HttpResponse.java new file mode 100644 index 0000000..65f5bc0 --- /dev/null +++ b/src/main/model/http/HttpResponse.java @@ -0,0 +1,34 @@ +package model.http; + +import java.util.ArrayList; + +public record HttpResponse(String version, int status, String reason, String body, ArrayList<Header> headers) { + // for constructing local error responses + public HttpResponse(int status, String reason) { + this("HTTP 1.1", status, reason, "", new ArrayList<Header>()); + } + + // probably inefficient but eh + public static HttpResponse parse(String response) throws InvalidResponseException { + try { + var split = response.split("\\r\\n\\r\\n"); + var lines = split[0].split("\\r\\n"); + var body = split[1]; + var start = lines[0].split(" ", 3); + var version = start[0]; + var status = Integer.parseInt(start[1]); + var reason = start[2]; + + var headers = new ArrayList<Header>(); + for (int i = 1; i < lines.length; i++) { + split = lines[i].split(": ", 2); + headers.add(new Header(split[0], split[1])); + } + return new HttpResponse(version, status, reason, body, headers); + } catch (IndexOutOfBoundsException | NumberFormatException e) { + throw new InvalidResponseException(); + } + } + + public static class InvalidResponseException extends Exception {} +} |