From 121fb00c303d89b18f61352a29b937da564414de Mon Sep 17 00:00:00 2001 From: Mauro Hernan Riva Date: Sat, 28 Oct 2017 20:54:58 +0200 Subject: [PATCH] added urequest.py --- urllib/urequest.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 urllib/urequest.py diff --git a/urllib/urequest.py b/urllib/urequest.py new file mode 100644 index 0000000..360afc9 --- /dev/null +++ b/urllib/urequest.py @@ -0,0 +1,65 @@ +import usocket + +def urlopen(url, data=None, method="GET"): + if data is not None and method == "GET": + method = "POST" + try: + proto, dummy, host, path = url.split("/", 3) + except ValueError: + proto, dummy, host = url.split("/", 2) + path = "" + if proto == "http:": + port = 80 + elif proto == "https:": + import ussl + port = 443 + else: + raise ValueError("Unsupported protocol: " + proto) + + if ":" in host: + host, port = host.split(":", 1) + port = int(port) + + ai = usocket.getaddrinfo(host, port) + addr = ai[0][4] + + s = usocket.socket() + try: + s.connect(addr) + if proto == "https:": + s = ussl.wrap_socket(s, server_hostname=host) + + s.write(method) + s.write(b" /") + s.write(path) + s.write(b" HTTP/1.0\r\nHost: ") + s.write(host) + s.write(b"\r\n") + + if data: + s.write(b"Content-Length: ") + s.write(str(len(data))) + s.write(b"\r\n") + s.write(b"\r\n") + if data: + s.write(data) + + l = s.readline() + protover, status, msg = l.split(None, 2) + status = int(status) + #print(protover, status, msg) + while True: + l = s.readline() + if not l or l == b"\r\n": + break + #print(l) + if l.startswith(b"Transfer-Encoding:"): + if b"chunked" in l: + raise ValueError("Unsupported " + l) + elif l.startswith(b"Location:"): + raise NotImplementedError("Redirects not yet supported") + except OSError: + s.close() + raise + + return s