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

相关推荐
巴巴_羊2 小时前
前端面经 计网 http和https区别
网络协议·http·https
码上淘金3 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo3 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552874 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
懵逼的小黑子4 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
Y3174294 小时前
Python Day23 学习
python·学习
Ai尚研修-贾莲5 小时前
Python语言在地球科学交叉领域中的应用——从数据可视化到常见数据分析方法的使用【实例操作】
python·信息可视化·数据分析·地球科学
格林威5 小时前
Baumer工业相机堡盟工业相机的工业视觉中为什么偏爱“黑白相机”
开发语言·c++·人工智能·数码相机·计算机视觉
橙子199110165 小时前
在 Kotlin 中什么是委托属性,简要说说其使用场景和原理
android·开发语言·kotlin
蓝婷儿5 小时前
前端面试每日三题 - Day 32
前端·面试·职场和发展