Python面试题:如何在 Python 中发送 HTTP 请求?

在 Python 中发送 HTTP 请求可以使用多个库,其中最常用的是 requests 库。这个库非常直观和易于使用,支持多种 HTTP 方法,如 GET、POST、PUT、DELETE 等。以下是如何使用 requests 库发送 HTTP 请求的一些示例:

安装 requests

在使用 requests 库之前,需要先安装它。你可以使用 pip 安装:

sh 复制代码
pip install requests

发送 HTTP 请求的示例

1. 发送 GET 请求

GET 请求用于从服务器获取数据。

python 复制代码
import requests

response = requests.get('https://api.example.com/data')
print(response.status_code)  # 输出状态码
print(response.text)  # 输出响应内容
2. 发送 POST 请求

POST 请求用于向服务器发送数据。

python 复制代码
import requests

data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/submit', data=data)
print(response.status_code)
print(response.json())  # 如果响应内容是 JSON 格式
3. 发送带有头部信息的请求

可以在请求中添加头部信息。

python 复制代码
import requests

headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.get('https://api.example.com/protected', headers=headers)
print(response.status_code)
print(response.text)
4. 发送带有 URL 参数的 GET 请求

可以在请求 URL 中添加查询参数。

python 复制代码
import requests

params = {'param1': 'value1', 'param2': 'value2'}
response = requests.get('https://api.example.com/data', params=params)
print(response.status_code)
print(response.text)
5. 处理 JSON 数据

发送 JSON 数据和处理 JSON 响应。

python 复制代码
import requests
import json

# 发送 JSON 数据
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/submit', json=data)
print(response.status_code)
print(response.json())

# 处理 JSON 响应
response = requests.get('https://api.example.com/data')
data = response.json()
print(data)
6. 上传文件

可以通过 POST 请求上传文件。

python 复制代码
import requests

files = {'file': open('report.csv', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
print(response.status_code)
print(response.text)
7. 超时设置

在请求中设置超时时间,以防止请求无限期挂起。

python 复制代码
import requests

try:
    response = requests.get('https://api.example.com/data', timeout=5)  # 超时时间为5秒
    print(response.status_code)
    print(response.text)
except requests.exceptions.Timeout:
    print('The request timed out')
8. 处理异常

处理可能发生的请求异常。

python 复制代码
import requests

try:
    response = requests.get('https://api.example.com/data')
    response.raise_for_status()  # 如果响应状态码不是 200,抛出异常
    print(response.status_code)
    print(response.text)
except requests.exceptions.HTTPError as errh:
    print('Http Error:', errh)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
except requests.exceptions.Timeout as errt:
    print('Timeout Error:', errt)
except requests.exceptions.RequestException as err:
    print('Something went wrong:', err)

总结

requests 库提供了一种简便的方法来发送 HTTP 请求,并且支持多种 HTTP 方法和功能。通过上述示例,你可以轻松地在 Python 中发送和处理 HTTP 请求。

相关推荐
Websites25 分钟前
Hyperf 百度翻译接口实现方案
开发语言·自然语言处理·php·自动翻译
码界筑梦坊30 分钟前
135-基于Spark的抖音数据分析热度预测系统
大数据·python·数据分析·spark·毕业设计·echarts
独行soc39 分钟前
2025年大模型安全岗的面试汇总(题目+回答)
android·人工智能·安全·面试·职场和发展·渗透测试
Blossom.1181 小时前
把大模型当“温度计”——基于 LLM 的分布式系统异常根因定位实战
人工智能·python·深度学习·机器学习·自然语言处理·分类·bert
papership2 小时前
【入门级-C++程序设计:11、指针与引用-引 用】
c语言·开发语言·c++·青少年编程
常乐か3 小时前
VS2022+QT5.15.2+OCCT7.9.1的开发环境搭建流程
开发语言·qt·opencascade
F_D_Z3 小时前
Encoder-Decoder Model编码器-解码器模型
python·深度学习·机器学习
Evand J4 小时前
【MATLAB例程】滑动窗口均值滤波、中值滤波、最小值/最大值滤波对比。附代码下载链接
开发语言·matlab·均值算法
IT毕设实战小研4 小时前
基于SpringBoot的救援物资管理系统 受灾应急物资管理系统 物资管理小程序
java·开发语言·vue.js·spring boot·小程序·毕业设计·课程设计