[RTL8722CSM] [RTL8722DM] Socket - 從HTTP網站獲取信息

材料準備

  • AmebaD[AMB21 / AMB22] x 1

範例準備

創建socket後,我們可以訪問HTTP網站並從中獲取信息。

在粘貼模式下,將以下代碼複製並粘貼到REPL中。

 1import socket
 2from wireless import WLAN
 3wifi = WLAN(mode = WLAN.STA)
 4wifi.connect(ssid = "YourWiFiSSID", pswd = "YourPassword") # change the ssid and pswd to yours
 5def http_get(url):
 6     _, _, host, path = url.split('/', 3)
 7     c = socket.SOCK()
 8     # We are visiting MicroPython official website's test page
 9     c.connect(host, 80)
10     c.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
11     while True:
12             data = c.recv(100)
13             if data:
14             print(str(data,'utf8'), end='')
15             else:
16             break
17http_get('http://micropython.org/ks/test.html')