toc HTTPS Tutorials & Examples > Network Protocols > HTTPS


Using HTTPS adds Transport Layer Security (TLS) to your network traffic. The advantage is an encrypted connection between your device and the server.

Basic example

from network import WLAN #note that you can also use LTE
import socket
import ssl
import time

wlan = WLAN()
wlan.init(mode=WLAN.STA, ssid='your ssid', auth=(WLAN.WPA2, 'your password'))
print("connecting", end='')
while not wlan.isconnected():
    print(".", end='')

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss = ssl.wrap_socket(s) #adds TLS
ss.connect(socket.getaddrinfo(host, 443)[0][-1])
httpreq = 'GET / HTTP/1.1 \r\nHOST: '+ host + '\r\nConnection: close \r\n\r\n'
rec = ss.recv(10000)

Basic connection using ssl.wrap_socket().

import socket
import ssl

s = socket.socket()
ss = ssl.wrap_socket(s)
ss.connect(socket.getaddrinfo('', 443)[0][-1])

Below is an example using certificates with the blynk cloud.

Certificate was downloaded from the blynk examples folder and placed in /flash/cert/ on the device.

import socket
import ssl

s = socket.socket()
ss = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='/flash/cert/ca.pem')
ss.connect(socket.getaddrinfo('', 8441)[0][-1])

For more info, check the ssl module in the API reference.


Previous Next