|
21 | 21 | requests = adafruit_requests.Session(pool, ssl_context) |
22 | 22 | rssi = wifi.radio.ap_info.rssi |
23 | 23 |
|
| 24 | +# URL for GET request |
24 | 25 | JSON_GET_URL = "https://httpbin.org/get" |
| 26 | +# Define a custom header as a dict. |
| 27 | +headers = {"user-agent": "blinka/1.0.0"} |
25 | 28 |
|
26 | 29 | print(f"\nConnecting to {ssid}...") |
27 | 30 | print(f"Signal Strength: {rssi}") |
|
34 | 37 |
|
35 | 38 | # Define a custom header as a dict. |
36 | 39 | headers = {"user-agent": "blinka/1.0.0"} |
37 | | -print(f" | Fetching JSON: {JSON_GET_URL}") |
38 | | - |
39 | | -# GET JSON |
40 | | -response = requests.get(JSON_GET_URL, headers=headers) |
41 | | -content_type = response.headers.get("content-type", "") |
42 | | -date = response.headers.get("date", "") |
43 | | - |
44 | | -json_data = response.json() |
45 | | -headers = json_data["headers"] |
46 | | - |
47 | | -# JSON Response |
48 | | -if response.status_code == 200: |
49 | | - print(f" | 🆗 Status Code: {response.status_code}") |
50 | | -else: |
51 | | - print(f" | | Status Code: {response.status_code}") |
52 | | -print(f" | | Custom User-Agent Header: {headers['User-Agent']}") |
53 | | -print(f" | | Content-Type: {content_type}") |
54 | | -print(f" | | Response Timestamp: {date}") |
55 | | - |
56 | | -# Close, delete and collect the response data |
57 | | -response.close() |
58 | | - |
59 | | -print(f" | ✂️ Disconnected from {JSON_GET_URL}") |
| 40 | +print(" | Fetching JSON data from %s..." % JSON_GET_URL) |
| 41 | + |
| 42 | +# Use with statement for retreiving GET request data |
| 43 | +with requests.get(JSON_GET_URL, headers=headers) as response: |
| 44 | + json_data = response.json() |
| 45 | + headers = json_data["headers"] |
| 46 | + content_type = response.headers.get("content-type", "") |
| 47 | + date = response.headers.get("date", "") |
| 48 | + if response.status_code == 200: |
| 49 | + print(f" | 🆗 Status Code: {response.status_code}") |
| 50 | + else: |
| 51 | + print(f" | | Status Code: {response.status_code}") |
| 52 | + print(f" | | Custom User-Agent Header: {headers['User-Agent']}") |
| 53 | + print(f" | | Content-Type: {content_type}") |
| 54 | + print(f" | | Response Timestamp: {date}") |
0 commit comments