Last active
February 11, 2022 04:32
-
-
Save anecdata/80bb4b685b19ca5d27f443d5e278d61e to your computer and use it in GitHub Desktop.
HTTPS request via TCP Socket - CircuitPython on Espressif
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# initial read only (typically headers) | |
import wifi | |
import socketpool | |
import ssl | |
import ipaddress | |
from secrets import secrets | |
HOST = "example.com" | |
PATH = "/" | |
PORT = 443 | |
TIMEOUT = 60 | |
MAXBUF = 4096 | |
print("Connecting to wifi") | |
wifi.radio.connect(secrets["ssid"], secrets["password"]) | |
pool = socketpool.SocketPool(wifi.radio) | |
print("Create TCP Client Socket") | |
sock = pool.socket(pool.AF_INET, pool.SOCK_STREAM) | |
context = ssl.create_default_context() | |
# context.check_hostname = False # can change dynamically (per-URL) | |
s = context.wrap_socket(sock, server_hostname=HOST) | |
s.settimeout(TIMEOUT) | |
print("Connecting") | |
s.connect((HOST, PORT)) | |
size = s.send(f"GET {PATH} HTTP/1.1\r\nHost: {HOST}:{PORT}\r\n\r\n".encode()) | |
print("Sent", size, "bytes") | |
# just get the first hunk and call it a day | |
buf = bytearray(MAXBUF) | |
size = s.recv_into(buf) | |
print('Received', size, "bytes", buf[:size]) | |
s.close() | |
print("Done-ish.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment