add easy way to add headers
add Connection header to add support for http 1.1
This commit is contained in:
parent
1ced8795ef
commit
57e1fae538
36
browser.py
36
browser.py
@ -20,7 +20,33 @@ class URL:
|
|||||||
self.host, port = self.host.split(":", 1)
|
self.host, port = self.host.split(":", 1)
|
||||||
self.port = int(port)
|
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(
|
s = socket.socket(
|
||||||
family=socket.AF_INET,
|
family=socket.AF_INET,
|
||||||
type=socket.SOCK_STREAM,
|
type=socket.SOCK_STREAM,
|
||||||
@ -31,10 +57,10 @@ class URL:
|
|||||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
|
||||||
s = context.wrap_socket(s, server_hostname=self.host)
|
s = context.wrap_socket(s, server_hostname=self.host)
|
||||||
|
|
||||||
request_str = f"GET {self.path} HTTP/1.0\r\n"
|
self.add_request_line(method)
|
||||||
request_str += f"Host: {self.host}\r\n"
|
self.add_default_headers()
|
||||||
request_str += "\r\n"
|
self.end_headers()
|
||||||
s.send(request_str.encode("utf8"))
|
s.send(self.request_string.encode("utf8"))
|
||||||
|
|
||||||
response = s.makefile("r", encoding="utf8", newline="\r\n")
|
response = s.makefile("r", encoding="utf8", newline="\r\n")
|
||||||
status_line = response.readline()
|
status_line = response.readline()
|
||||||
|
Loading…
Reference in New Issue
Block a user