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

相关推荐
q567315231 分钟前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
会的全对٩(ˊᗜˋ*)و10 分钟前
【数据挖掘】数据挖掘综合案例—银行精准营销
人工智能·经验分享·python·数据挖掘
___波子 Pro Max.29 分钟前
GitHub Actions配置python flake8和black
python·black·flake8
rzl021 小时前
java web5(黑马)
java·开发语言·前端
时序数据说1 小时前
为什么时序数据库IoTDB选择Java作为开发语言
java·大数据·开发语言·数据库·物联网·时序数据库·iotdb
jingling5551 小时前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架
莫空00001 小时前
深入理解JavaScript属性描述符:从数据属性到存取器属性
前端·面试
00后程序员张1 小时前
免Mac上架实战:全平台iOS App上架流程的工具协作经验
websocket·网络协议·tcp/ip·http·网络安全·https·udp
阿蒙Amon1 小时前
【Python小工具】使用 OpenCV 获取视频时长的详细指南
python·opencv·音视频
m0_687399841 小时前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg