Python uses Requests to add request headers and body
Preparation work for environmental construction:
1. Install Python: First, you need to install Python on your computer. You can access it from the official website( https://www.python.org )Download and install the Python version suitable for your operating system.
2. Install the Requests library: Use the following command to install the Requests library.
pip install requests
3. Import Requests Library: In Python code, you need to import the Requests library to use its functions and classes.
import requests
The sample code is as follows:
python
import requests
#Build Request Header
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'
}
#Build Request Body
payload = {
'key1': 'value1',
'key2': 'value2'
}
#Send GET request
response = requests.get(url, headers=headers)
#Send POST request
# response = requests.post(url, headers=headers, data=payload)
#Print response content
print(response.text)
Explanation and Summary:
1. To import the 'requests' library, we first need to import the' requests' library so that we can use its functions and classes to send HTTP requests.
2. Build request headers that contain information about user agents, Accept Language, and other HTTP requests.
3. Build a payload that contains the data we want to send, which is typically used to send POST requests.
4. Send a GET or POST request, using the 'requests. get()' function to send the GET request, and the 'requests. post()' function to send the POST request. It should be noted that we need to pass the URL, request header, and request body as parameters to these functions.
5. To print the response content, we can use 'response. text' to obtain the response content and print it out.
Through the above steps, we can successfully add the request header and request body, and send the HTTP request. Based on actual needs, you can modify the content of the request header and request body as needed.