Example explanation 14-http_client_ssl http client encryption

# 简单的HTTPS客户端示例。

import network
import socket
import ssl
import time

# AP info
SSID = ""  # Network SSID
KEY = ""  # Network key

PORT = 443
HOST = "www.google.com"

# 初始化wlan模块并连接到网络
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, KEY)

while not wlan.isconnected():
    print('Trying to connect to "{:s}"...'.format(SSID))
    time.sleep_ms(1000)

# 我们现在应该有一个通过DHCP的有效IP了
print("WiFi Connected ", wlan.ifconfig())

# 通过DNS获取addr信息
addr = socket.getaddrinfo(HOST, PORT)[0][4]
print(addr)

# 创建一个新的套接字并连接到addr
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect(addr)

# 设置超时
client.settimeout(3.0)

client = ssl.wrap_socket(client, server_hostname=HOST)

# 发送HTTP请求和recv响应
request = "GET / HTTP/1.1\r\n"
request += "HOST: %s\r\n"
request += "User-Agent: Mozilla/5.0\r\n"
request += "Connection: keep-alive\r\n\r\n"
# 如果需要,添加更多的headers。
client.write(request % (HOST) + "\r\n")

response = client.read(1024)
for l in response.split(b"\r\n"):
    print(l.decode())

# 关闭套接字
client.close()

results matching ""

    No results matching ""