HTTP-Client Example Explanation#
Environment Preparation#
First, ensure that the CanMV development board is connected to a router or switch via the network port, and the router can function properly with the ability to access the internet. This is the basic environment setup for making HTTP requests.
Example Explanation#
The following Python example demonstrates how to implement an HTTP client on the CanMV development board. Through this client, an HTTP GET request is sent to a specified server (here, Baidu), and the response content is received.
Importing Necessary Modules#
import network
import socket
The
networkmodule is used to manage network interfacesThe
socketmodule provides low-level interfaces for network communication.
Defining the Main Function#
def main(use_stream=True):
# ...(后续代码)
The function main defines the parameter use_stream that determines whether to use the streaming interface to read response data, with a default value of True, used to control the data reception method.
Configuring the Network Interface#
def network_use_wlan(is_wlan=True):
if is_wlan:
sta = network.WLAN(0)
sta.connect("TEST", "12345678")
print(sta.status())
while sta.ifconfig()[0] == '0.0.0.0':
os.exitpoint()
print(sta.ifconfig())
ip = sta.ifconfig()[0]
return ip
else:
a = network.LAN()
if not a.active():
raise RuntimeError("LAN interface is not active.")
a.ifconfig("dhcp")
print(a.ifconfig())
ip = a.ifconfig()[0]
return ip
This function configures the network interface based on input:
WLAN Mode: Connects to a specified Wi-Fi (SSID is “TEST”) through a wireless network interface (WLAN).
LAN Mode: Automatically obtains an IP address through a wired network interface (LAN).
Creating and Configuring the Socket#
# 创建 socket 对象
s = socket.socket()
# 获取目标地址和端口号
ai = []
for attempt in range(0, 3):
try:
ai = socket.getaddrinfo("www.baidu.com", 80)
break
except:
print("getaddrinfo again")
if ai == []:
print("连接错误")
s.close()
return
addr = ai[0][-1]
print("连接地址:", addr)
A socket object is created, and the getaddrinfo function is used to obtain the address and port number information of the server (Baidu). A retry mechanism is used to improve robustness.
Sending HTTP Request and Receiving Response#
# 连接到服务器
s.connect(addr)
if use_stream:
# 使用流式接口读取响应
s = s.makefile("rwb", 0)
s.write(b"GET /index.html HTTP/1.0\r\n\r\n")
print(s.read())
else:
# 直接使用 socket 接口发送和接收数据
s.send(b"GET /index.html HTTP/1.0\r\n\r\n")
print(s.recv(4096))
# 关闭 socket
s.close()
The code selects whether to use the streaming interface or directly use the socket interface to send HTTP requests and read response data based on the use_stream parameter.
Function Call#
# 分别测试流式接口和非流式接口
main(use_stream=True)
main(use_stream=False)
Call the main function with different use_stream parameters to test the effects of streaming and non-streaming HTTP response reading. If use_stream is True, the streaming interface is used to send the request and read the entire response; if it is False, the request is sent directly and a response of a certain length (4096 bytes in this example) is received. Finally, the socket connection is closed to release resources.
Complete Example#
import network
import socket
import os, time
def network_use_wlan(is_wlan=True):
if is_wlan:
sta = network.WLAN(0)
sta.connect("TEST", "12345678")
print(sta.status())
while sta.ifconfig()[0] == '0.0.0.0':
os.exitpoint()
print(sta.ifconfig())
ip = sta.ifconfig()[0]
return ip
else:
a = network.LAN()
if not a.active():
raise RuntimeError("LAN interface is not active.")
a.ifconfig("dhcp")
print(a.ifconfig())
ip = a.ifconfig()[0]
return ip
def main(use_stream=True):
# 获取 LAN 接口
network_use_wlan(True)
# 创建 socket
s = socket.socket()
# 获取地址及端口号
ai = []
for attempt in range(0, 3):
try:
ai = socket.getaddrinfo("www.baidu.com", 80)
break
except:
print("getaddrinfo again")
if ai == []:
print("连接错误")
s.close()
return
addr = ai[0][-1]
print("连接地址:", addr)
# 连接
s.connect(addr)
if use_stream:
s = s.makefile("rwb", 0)
s.write(b"GET /index.html HTTP/1.0\r\n\r\n")
print(s.read())
else:
s.send(b"GET /index.html HTTP/1.0\r\n\r\n")
print(s.recv(4096))
s.close()
# main()
main(use_stream=True)
main(use_stream=False)
For specific interface definitions, please refer to socket、network.
