Skip to content

Commit a8ab5d7

Browse files
authored
Http client example (#404)
* added http client example * result description
1 parent 2067ed9 commit a8ab5d7

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed
Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,37 @@
11
---
22
Title: 'HTTP Client'
33
---
4-
In this example, we discuss how to access information served on the internet. Once you have connected to either WiFi or LTE, it is possible to access any webpage. Now there is no such thing as a webbrowser like Chrome or Firefox in your device, and the REPL is not that great at rendering webpages either, so we are mainly looking at the source of the page here.
4+
In this example, we discuss how to access information served on the internet. Once you have connected to either WiFi or LTE, it is possible to access any webpage. Now there is no such thing as a webbrowser like Chrome or Firefox in your device, and the REPL is not that great at rendering webpages either, so we are mainly looking at the source of the page here. Though for sending and receiving sensor measurements, this can be very useful. The example below connects to `pycom.io` using the HTTP protocol. Note that we use the `ssl` library to wrap the socket with for use with HTTPS, as it is required by most webservices nowadays. The example will print out the received data from the webserver, which in this case, is the index page's source.
55

6-
For example, we can use the socket to render
7-
...
6+
7+
```python
8+
#setup internet connection
9+
from network import WLAN
10+
import time
11+
import socket
12+
import ssl
13+
wlan = WLAN()
14+
wlan.connect(ssid='', auth=(WLAN.WPA2, ''))
15+
print('connecting..',end='')
16+
while not wlan.isconnected():
17+
time.sleep(1)
18+
print('.',end='')
19+
20+
print('connected')
21+
# setup socket for connection
22+
s = socket.socket()
23+
s = ssl.wrap_socket(s)
24+
host = 'pycom.io'
25+
addr = socket.getaddrinfo(host,443)[0][-1]
26+
s.connect(addr)
27+
print('socket connected')
28+
# it is possible to attach additional HTTP headers in the line below, but note to always close with \r\n\r\n
29+
httpreq = 'GET / HTTP/1.1 \r\nHOST: '+ host + '\r\nConnection: close \r\n\r\n'
30+
print('http request: \n', httpreq)
31+
s.send(httpreq)
32+
time.sleep(1)
33+
rec_bytes = s.recv(10000)
34+
print(rec_bytes)
35+
print('end')
36+
37+
```

0 commit comments

Comments
 (0)