Python uses Requests to send HTTP requests, supporting GET and POST
Preparation work:
1. Install Python: You can go to the official Python website( https://www.python.org/ )Download the latest version of Python and install it.
2. Install the Requests library: Execute the 'pip install requests' command from the command line to install the Requests library.
Sample code (sending GET request):
python
import requests
def send_get_request(url):
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return None
#Example: Sending a GET request to obtain Baidu homepage content and printing it
url = 'https://www.baidu.com'
content = send_get_request(url)
if content:
print(content)
Sample code (sending POST request):
python
import requests
def send_post_request(url, data):
response = requests.post(url, data=data)
if response.status_code == 200:
return response.text
else:
return None
#Example: Sending a POST request to submit form data and printing the response content
url = 'http://www.example.com/submit'
data = {'username': 'John', 'password': 'secret'}
content = send_post_request(url, data)
if content:
print(content)
Summary:
The Requests library allows for easy sending of HTTP requests, supporting GET, POST, and other commonly used request methods. By calling the corresponding request method, the request can be sent and the server's response obtained. When sending a GET request, you can directly use the 'requests. get()' method and pass in the target URL; When sending a POST request, you can use the 'requests. post()' method and pass the form data to the request through the 'data' parameter. Based on the response status code of the server, it is possible to determine whether the request was successful and obtain the returned content.