163 lines
5.8 KiB
Python
Raw Normal View History

2024-12-21 18:37:51 +00:00
# Written by retoor@molodetz.nl
# This script implements a simple HTTP client capable of sending a GET request to a specified URL and receiving the response.
# The script uses the 'socket' import from Python's standard library.
# MIT License:
2024-12-21 19:49:14 +00:00
#
2024-12-21 18:37:51 +00:00
# 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:
2024-12-21 19:49:14 +00:00
#
2024-12-21 18:37:51 +00:00
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
2024-12-21 19:49:14 +00:00
#
2024-12-21 18:37:51 +00:00
# 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
class Socket:
def __init__(self, host, port):
self.socket = socket.socket()
self.host = host
self.port = port
self.buffer = b''
def connect(self):
self.socket.connect((self.host, self.port))
def write(self, data):
if hasattr(data, "encode"):
data = data.encode()
self.socket.sendall(data)
def read(self, size=4096, exactly=False):
while len(self.buffer) < size:
self.buffer += self.socket.recv(size - len(self.buffer))
if not exactly:
break
if len(self.buffer) >= size:
chunk = self.buffer[:size]
self.buffer = self.buffer[size:]
return chunk
chunk = self.buffer
self.buffer = b''
return chunk
def read_until(self, until):
while until not in self.buffer:
self.buffer += self.socket.recv(1024)
data = self.buffer[:self.buffer.find(until)]
self.buffer = self.buffer[len(data) + len(until):]
return data
def close(self):
self.socket.close()
class Url:
def __init__(self, url):
self.url = url
@property
def schema(self):
return self.url[:self.url.find("://")]
@property
def host(self):
return self.url[len(self.schema) + 3:].split("/")[0].split(":")[0]
@property
def hostname(self):
return f"{self.host}:{self.port}"
@property
def port(self):
try:
return int(self.url[len(self.schema) + 3:].split("/")[0].split(":")[1])
except IndexError:
pass
if self.schema in ["ws", "http", "dav"]:
return 80
if self.schema in ["wss", "https", "davs"]:
return 443
raise Exception("Couldn't resolve port.")
@property
def path(self):
2024-12-21 19:49:14 +00:00
return "/".join(self.url.split("/")[3:]) or "/"
2024-12-21 18:37:51 +00:00
class HTTPResponse:
def __init__(self, headers):
2024-12-21 19:49:14 +00:00
self.header_string = headers
self.line, self.headers = self.parse_headers(self.header_string)
2024-12-21 18:37:51 +00:00
self.body = b''
2024-12-21 19:49:14 +00:00
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
2024-12-21 18:37:51 +00:00
@property
def json(self):
return json.loads(self.body)
def __str__(self):
if self.body and self.body[0] in [b'{', b'[']:
return json.dumps(json.loads(self.body.decode()), indent=2)
return self.body.decode(errors='ignore')
class HTTPRequest:
def __init__(self, url):
self.url = Url(url)
2024-12-21 19:49:14 +00:00
self.socket = None
2024-12-21 18:37:51 +00:00
self.request_headers = '\r\n'.join([
f"GET {self.url.path} HTTP/1.1",
f"Host: {self.url.hostname}",
"Connection: keep-alive",
"\r\n"
]).encode()
self.response = None
def get(self):
2024-12-21 19:49:14 +00:00
if not self.socket:
self.socket = Socket(self.url.host, self.url.port)
self.socket.connect()
2024-12-21 18:37:51 +00:00
self.socket.write(self.request_headers)
response_headers = self.socket.read_until(b"\r\n\r\n")
self.response = HTTPResponse(response_headers)
data = b''
2024-12-21 19:49:14 +00:00
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
2024-12-21 18:37:51 +00:00
self.response.body = data
return self.response
2024-12-21 19:49:14 +00:00
if __name__ == '__main__':
http = HTTPRequest("http://localhost:8082/")
print(http.get())