add easy way to add headers

add Connection header to add support for http 1.1
This commit is contained in:
Matthew Welch 2024-11-28 16:40:02 -08:00
parent 1ced8795ef
commit 57e1fae538

View File

@ -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()