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 请求。

相关推荐
张子夜 iiii几秒前
传统神经网络实现-----手写数字识别(MNIST)项目
人工智能·pytorch·python·深度学习·算法
A尘埃6 分钟前
智能工单路由系统(Java)
java·开发语言·智能工单
Rhys..8 分钟前
python + Flask模块学习 1 基础用法
python·学习·前端框架·flask
飞翔的佩奇10 分钟前
【完整源码+数据集+部署教程】骰子点数识别图像实例分割系统源码和数据集:改进yolo11-DCNV2
python·yolo·计算机视觉·数据集·yolo11·骰子点数识别图像实例分割
Source.Liu17 分钟前
【Python基础】 13 Rust 与 Python 注释对比笔记
开发语言·笔记·python·rust
qq_1955516928 分钟前
代码随想录70期day3
开发语言·python
XXYBMOOO33 分钟前
Qt UDP 通信类详解与实现
开发语言·网络·c++·qt·网络协议·ui·udp
pusue_the_sun38 分钟前
C语言强化训练(12)
c语言·开发语言·算法
JosieBook1 小时前
【SpringBoot】21-Spring Boot中Web页面抽取公共页面的完整实践
前端·spring boot·python
UrbanJazzerati1 小时前
掌握 xlwings 的 used_range:高效处理 Excel 数据区域
python·面试·excel