在Python中发起网络请求,你可以使用`requests`库。以下是一些基本的网络请求设置示例:
基本GET请求
import requests
目标URL
url = "https://api.example.com/data"
发起GET请求
response = requests.get(url)
打印响应的文本内容
print(response.text)
带参数的GET请求
import requests
目标URL
url = "https://example.com/search"
要发送的查询参数
params = {'key': 'value'}
发起GET请求
response = requests.get(url, params=params)
打印响应的文本内容
print(response.text)
POST请求
import requests
目标URL
url = "https://example.com/login"
要发送的数据
data = {'username': 'learner'}
发起POST请求
response = requests.post(url, data=data)
打印响应的文本内容
print(response.text)
自定义请求头
import requests
目标URL
url = "https://example.com"
设置请求头
headers = {'User-Agent': 'MyBot/0.1'}
发起GET请求
response = requests.get(url, headers=headers)
打印响应的文本内容
print(response.text)
处理JSON响应
import requests
目标URL
url = "https://api.example.com/data"
发起GET请求
response = requests.get(url)
直接用.json()方法处理JSON响应
print(response.json())
使用Flask框架监听网络请求
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
处理GET请求
return 'Hello, GET request!'
elif request.method == 'POST':
处理POST请求
data = request.get_json()
return 'Hello, POST request! Data: {}'.format(data)
else:
不支持的请求方法
return 'Unsupported request method'
if __name__ == '__main__':
app.run()
以上示例展示了如何使用`requests`库进行基本的网络请求设置,包括GET和POST请求,以及如何处理响应。如果你需要更高级的功能,比如自定义请求头、处理cookies、超时设置等,`requests`库也提供了相应的参数和方法