|
# 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:
|
|
|
|
# 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
|
|
|
|
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):
|
|
return self.url[len(self.schema) + 3 + len(str(self.port)):] or "/"
|
|
|
|
class HTTPResponse:
|
|
def __init__(self, headers):
|
|
self.headers = headers
|
|
self.body = b''
|
|
|
|
@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)
|
|
self.socket = Socket(self.url.host, self.url.port)
|
|
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):
|
|
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()
|
|
self.response.body = data
|
|
return self.response
|
|
|
|
http = HTTPRequest("http://localhost:8082/")
|
|
print(http.get()) |