Example code of Python requests module
Here is a simple example code demonstrating how to send HTTP requests using the requests module in Python.
import requests
# 发送GET请求
response = requests.get("http://www.example.com")
print(response.status_code) # 打印响应状态码
print(response.text) # 打印响应内容
# 发送POST请求
data = {"username": "admin", "password": "123456"}
response = requests.post("http://www.example.com/login", data=data)
print(response.status_code) # 打印响应状态码
print(response.json()) # 打印响应内容,假设返回的是JSON格式数据
# 发送带有请求头的GET请求
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
response = requests.get("http://www.example.com", headers=headers)
print(response.status_code) # 打印响应状态码
print(response.text) # 打印响应内容
In the above code, we first use the requests.get() method to send a GET request. The response object returned can be accessed using the .status_code attribute to get the response status code, and the .text attribute to get the response content.
Next, send a POST request using the requests.post() method and pass the form data in dictionary form to the data parameter, then retrieve the response status code and content using the .status_code attribute and .json() method.
Finally, by sending a GET request with a request header, you can pass the request header as a dictionary to the “headers” parameter. You can also obtain the response status code and content using the .status_code and .text attributes.