diff --git a/scripts/examples/14-WiFi-Shield/tcp_client.py b/scripts/examples/14-WiFi-Shield/http_client.py similarity index 70% rename from scripts/examples/14-WiFi-Shield/tcp_client.py rename to scripts/examples/14-WiFi-Shield/http_client.py index 2163cdbad..96c8f94dd 100644 --- a/scripts/examples/14-WiFi-Shield/tcp_client.py +++ b/scripts/examples/14-WiFi-Shield/http_client.py @@ -1,6 +1,4 @@ -# TCP Client Example -# -# This example shows how to send and receive TCP traffic with the WiFi shield. +# Simple HTTP client example. import network, usocket @@ -8,6 +6,9 @@ import network, usocket SSID='' # Network SSID KEY='' # Network key +PORT = 80 +HOST = "www.google.com" + # Init wlan module and connect to network print("Trying to connect... (may take a while)...") @@ -18,17 +19,18 @@ wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) print(wlan.ifconfig()) # Get addr info via DNS -addr = usocket.getaddrinfo("www.google.com", 80)[0][4] +addr = usocket.getaddrinfo(HOST, PORT)[0][4] +print(addr) # Create a new socket and connect to addr client = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) client.connect(addr) -# Set timeout to 1s -client.settimeout(1.0) +# Set timeout +client.settimeout(3.0) # Send HTTP request and recv response -client.send("GET / HTTP/1.0\r\n\r\n") +client.send("GET / HTTP/1.1\r\nHost: %s\r\n\r\n"%(HOST)) print(client.recv(1024)) # Close socket diff --git a/scripts/examples/14-WiFi-Shield/http_client_ssl.py b/scripts/examples/14-WiFi-Shield/http_client_ssl.py new file mode 100644 index 000000000..794aba680 --- /dev/null +++ b/scripts/examples/14-WiFi-Shield/http_client_ssl.py @@ -0,0 +1,48 @@ +# Simple HTTPS client example. + +import network, usocket, ussl + +# AP info +SSID="" # Network SSID +KEY="" # Network key + +PORT = 443 +HOST = "www.google.com" + +# Init wlan module and connect to network +print("Trying to connect... (may take a while)...") + +wlan = network.WINC() +wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK) + +# We should have a valid IP now via DHCP +print(wlan.ifconfig()) + +# Get addr info via DNS +addr = usocket.getaddrinfo(HOST, PORT)[0][4] +print(addr) + +# Create a new socket and connect to addr +client = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM) + +client.connect(addr) + +# Set timeout +client.settimeout(3.0) + +client = ussl.wrap_socket(client, server_hostname=HOST) + +# Send HTTP request and recv response +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" +# Add more headers if needed. +client.write(request%(HOST)+"\r\n") + +response = client.read(1024) +for l in response.split(b"\r\n"): + print(l.decode()) + +# Close socket +client.close()