2024-08-03 16:06:52 +10:00
|
|
|
# Very simple HTTPS client example:
|
|
|
|
|
# - Connects to a server.
|
|
|
|
|
# - Upgrades the connection to a TLS connection.
|
|
|
|
|
# - Sends a HTTP request.
|
|
|
|
|
# - Reads the result.
|
|
|
|
|
#
|
|
|
|
|
# This example works in both MicroPython and CPython.
|
|
|
|
|
#
|
|
|
|
|
# To implement an HTTPS client using less code, use mip to install the requests package:
|
|
|
|
|
# https://github.com/micropython/micropython-lib/tree/master/python-ecosys/requests
|
|
|
|
|
|
2022-08-19 22:58:37 +10:00
|
|
|
import socket
|
|
|
|
|
import ssl
|
2016-04-02 23:19:03 +03:00
|
|
|
|
|
|
|
|
|
2024-08-03 16:06:52 +10:00
|
|
|
# `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=True):
|
|
|
|
|
# Lookup the server address, for the given family and socket type.
|
|
|
|
|
ai = socket.getaddrinfo(domain, 443, addr_family, socket.SOCK_STREAM)
|
2016-04-02 23:19:03 +03:00
|
|
|
print("Address infos:", ai)
|
|
|
|
|
|
2024-08-03 16:06:52 +10:00
|
|
|
# Select the first address.
|
|
|
|
|
ai = ai[0]
|
|
|
|
|
|
|
|
|
|
# Create a socket with the server's family, type and proto.
|
|
|
|
|
s = socket.socket(ai[0], ai[1], ai[2])
|
|
|
|
|
|
|
|
|
|
# Connect to the server.
|
|
|
|
|
addr = ai[-1]
|
2016-04-02 23:19:03 +03:00
|
|
|
print("Connect address:", addr)
|
|
|
|
|
s.connect(addr)
|
|
|
|
|
|
2024-08-03 16:06:52 +10:00
|
|
|
# Upgrade the socket to a TLS connection.
|
2024-08-03 16:20:25 +10:00
|
|
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
|
|
|
ctx.check_hostname = False
|
|
|
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
|
|
|
s = ctx.wrap_socket(s)
|
2016-04-02 23:19:03 +03:00
|
|
|
print(s)
|
|
|
|
|
|
2024-08-03 16:06:52 +10:00
|
|
|
# Send request and read response.
|
2016-04-02 23:19:03 +03:00
|
|
|
if use_stream:
|
|
|
|
|
# Both CPython and MicroPython SSLSocket objects support read() and
|
|
|
|
|
# write() methods.
|
2016-10-09 19:36:04 +03:00
|
|
|
s.write(b"GET / HTTP/1.0\r\n\r\n")
|
2016-04-02 23:19:03 +03:00
|
|
|
print(s.read(4096))
|
|
|
|
|
else:
|
|
|
|
|
# MicroPython SSLSocket objects implement only stream interface, not
|
|
|
|
|
# socket interface
|
2016-10-09 19:36:04 +03:00
|
|
|
s.send(b"GET / HTTP/1.0\r\n\r\n")
|
2016-04-02 23:19:03 +03:00
|
|
|
print(s.recv(4096))
|
|
|
|
|
|
2024-08-03 16:06:52 +10:00
|
|
|
# Close the socket.
|
2016-07-23 00:41:19 +03:00
|
|
|
s.close()
|
|
|
|
|
|
2016-04-02 23:19:03 +03:00
|
|
|
|
2024-08-03 16:06:52 +10:00
|
|
|
main("google.com")
|