diff --git a/http-chunked.py b/httpr.py similarity index 68% rename from http-chunked.py rename to httpr.py index 8202656..d5905ff 100644 --- a/http-chunked.py +++ b/httpr.py @@ -5,14 +5,13 @@ # The script uses the 'socket' import from Python's standard library. # MIT License: - +# # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - +# # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - +# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - import socket import json @@ -85,12 +84,31 @@ class Url: @property def path(self): - return self.url[len(self.schema) + 3 + len(str(self.port)):] or "/" + return "/".join(self.url.split("/")[3:]) or "/" class HTTPResponse: def __init__(self, headers): - self.headers = headers + self.header_string = headers + self.line, self.headers = self.parse_headers(self.header_string) self.body = b'' + self.content_length = self.headers.get("Content-Length", 0) + self.transfer_encoding = self.headers.get("Transfer-Encoding", "") + self.connection = self.headers.get("Connection", "") + self.keep_alive = self.connection == "keep-alive" + self.is_chunked = self.transfer_encoding == "chunked" + + def __getitem__(self, key): + return self.headers[key] + + def parse_headers(self, headers): + header_dict = {} + line, *headers = headers.split(b"\r\n") + for header_line in headers: + key, *value = header_line.split(b": ") + key = key.decode() + value = ": ".join([value.decode() for value in value]) + header_dict[key] = int(value) if value.isdigit() else value + return line.decode(), header_dict @property def json(self): @@ -104,7 +122,7 @@ class HTTPResponse: class HTTPRequest: def __init__(self, url): self.url = Url(url) - self.socket = Socket(self.url.host, self.url.port) + self.socket = None self.request_headers = '\r\n'.join([ f"GET {self.url.path} HTTP/1.1", f"Host: {self.url.hostname}", @@ -114,24 +132,32 @@ class HTTPRequest: self.response = None def get(self): - self.socket.connect() + if not self.socket: + self.socket = Socket(self.url.host, self.url.port) + self.socket.connect() self.socket.write(self.request_headers) response_headers = self.socket.read_until(b"\r\n\r\n") self.response = HTTPResponse(response_headers) data = b'' - while True: - length = self.socket.read_until(b"\r\n") - length = int(length, 16) - chunk = self.socket.read(length + 2, exactly=True) - if isinstance(chunk, bytes): - data += chunk - else: - break - if chunk == b'\r\n': - break - self.socket.close() + if self.response.is_chunked: + while True: + length = self.socket.read_until(b"\r\n") + length = int(length, 16) + chunk = self.socket.read(length + 2, exactly=True) + if isinstance(chunk, bytes): + data += chunk + else: + break + if chunk == b'\r\n': + break + elif self.response.content_length: + data = self.socket.read(self.response.content_length) + if not self.response.keep_alive: + self.socket.close() + self.socket = None self.response.body = data return self.response -http = HTTPRequest("http://localhost:8082/") -print(http.get()) \ No newline at end of file +if __name__ == '__main__': + http = HTTPRequest("http://localhost:8082/") + print(http.get()) \ No newline at end of file