summaryrefslogtreecommitdiffstatshomepage
path: root/examples/network/http_client.py
diff options
context:
space:
mode:
authorDamien George <damien@micropython.org>2024-08-14 11:43:22 +1000
committerDamien George <damien@micropython.org>2024-08-28 12:28:58 +1000
commitfd03a0587f7303d2b37d69c85a1e079088c3de6c (patch)
tree305c333f2eedb3bafe78d09cdd0707f70858230d /examples/network/http_client.py
parentd75705311ad9406bbb03ae1d510693356cd4f1e3 (diff)
downloadmicropython-fd03a0587f7303d2b37d69c85a1e079088c3de6c.tar.gz
micropython-fd03a0587f7303d2b37d69c85a1e079088c3de6c.zip
examples/network: Support full URLs in HTTP(S) client examples.
Not just the domain name. This gives better HTTP 1.0 examples if someone wants to copy them. Signed-off-by: Damien George <damien@micropython.org>
Diffstat (limited to 'examples/network/http_client.py')
-rw-r--r--examples/network/http_client.py15
1 files changed, 10 insertions, 5 deletions
diff --git a/examples/network/http_client.py b/examples/network/http_client.py
index 879cddcd81..b16f87a981 100644
--- a/examples/network/http_client.py
+++ b/examples/network/http_client.py
@@ -13,9 +13,13 @@ import socket
# `addr_family` selects IPv4 vs IPv6: 0 means either, or use
# socket.AF_INET or socket.AF_INET6 to select a particular one.
-def main(domain, addr_family=0, use_stream=False):
+def main(url, addr_family=0, use_stream=False):
+ # Split the given URL into components.
+ proto, _, host, path = url.split(b"/", 3)
+ assert proto == b"http:"
+
# Lookup the server address, for the given family and socket type.
- ai = socket.getaddrinfo(domain, 80, addr_family, socket.SOCK_STREAM)
+ ai = socket.getaddrinfo(host, 80, addr_family, socket.SOCK_STREAM)
print("Address infos:", ai)
# Select the first address.
@@ -30,18 +34,19 @@ def main(domain, addr_family=0, use_stream=False):
s.connect(addr)
# Send request and read response.
+ request = b"GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host)
if use_stream:
# MicroPython socket objects support stream (aka file) interface
# directly, but the line below is needed for CPython.
s = s.makefile("rwb", 0)
- s.write(b"GET / HTTP/1.0\r\n\r\n")
+ s.write(request)
print(s.read())
else:
- s.send(b"GET / HTTP/1.0\r\n\r\n")
+ s.send(request)
print(s.recv(4096))
# Close the socket.
s.close()
-main("google.com")
+main(b"http://www.google.com/")