2015-11-21 00:20:28 +00:00
|
|
|
import usocket
|
|
|
|
|
2016-03-14 02:49:16 +00:00
|
|
|
def urlopen(url, data=None, method="GET"):
|
2016-04-16 18:30:54 +00:00
|
|
|
if data is not None and method == "GET":
|
2016-03-02 20:54:46 +00:00
|
|
|
method = "POST"
|
2015-11-21 00:20:28 +00:00
|
|
|
try:
|
|
|
|
proto, dummy, host, path = url.split("/", 3)
|
|
|
|
except ValueError:
|
|
|
|
proto, dummy, host = url.split("/", 2)
|
|
|
|
path = ""
|
|
|
|
if proto != "http:":
|
|
|
|
raise ValueError("Unsupported protocol: " + proto)
|
|
|
|
|
|
|
|
ai = usocket.getaddrinfo(host, 80)
|
|
|
|
addr = ai[0][4]
|
|
|
|
s = usocket.socket()
|
|
|
|
s.connect(addr)
|
2016-03-02 20:54:46 +00:00
|
|
|
if data:
|
|
|
|
req = b"%s /%s HTTP/1.0\r\nHost: %s\r\nContent-Length: %d\r\n\r\n" % (method, path, host, len(data))
|
|
|
|
else:
|
|
|
|
req = b"%s /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (method, path, host)
|
|
|
|
s.send(req)
|
|
|
|
if data:
|
|
|
|
s.send(data)
|
2015-11-21 00:20:28 +00:00
|
|
|
|
|
|
|
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(line)
|
|
|
|
if l.startswith(b"Transfer-Encoding:"):
|
|
|
|
if b"chunked" in line:
|
|
|
|
raise ValueError("Unsupported " + l)
|
|
|
|
elif l.startswith(b"Location:"):
|
|
|
|
raise NotImplementedError("Redirects not yet supported")
|
|
|
|
|
|
|
|
return s
|