From 57e1fae53859f9ecdbe72a4adafb59b36c3b60d0 Mon Sep 17 00:00:00 2001 From: Matthew Welch Date: Thu, 28 Nov 2024 16:40:02 -0800 Subject: [PATCH] add easy way to add headers add Connection header to add support for http 1.1 --- browser.py | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/browser.py b/browser.py index ce31852..0ad9f2a 100644 --- a/browser.py +++ b/browser.py @@ -20,7 +20,33 @@ class URL: self.host, port = self.host.split(":", 1) self.port = int(port) - def request(self) -> str: + self.request_string = "" + self.http_version = "HTTP/1.1" + self.headers = {"Host": self.host} + + def add_request_line(self, method): + self.request_string += f"{method} {self.path} {self.http_version}\r\n" + + def add_header(self, key, value): + self.headers[key] = value + + def add_headers(self, headers: dict[str,str]): + self.headers.update(headers) + + def add_default_headers(self): + self.add_headers({ + "Connection": "close", + "User-Agent": "PyWebBrowser" + }) + + def end_headers(self): + for key, value in self.headers.items(): + self.request_string += f"{key}: {value}\r\n" + self.request_string += "\r\n" + + def request(self, method: str = "GET", headers: dict = None) -> str: + if headers is not None: + self.add_headers(headers) s = socket.socket( family=socket.AF_INET, type=socket.SOCK_STREAM, @@ -31,10 +57,10 @@ class URL: context = ssl.SSLContext(ssl.PROTOCOL_TLS) s = context.wrap_socket(s, server_hostname=self.host) - request_str = f"GET {self.path} HTTP/1.0\r\n" - request_str += f"Host: {self.host}\r\n" - request_str += "\r\n" - s.send(request_str.encode("utf8")) + self.add_request_line(method) + self.add_default_headers() + self.end_headers() + s.send(self.request_string.encode("utf8")) response = s.makefile("r", encoding="utf8", newline="\r\n") status_line = response.readline()