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

相关推荐
AIAdvocate1 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼1 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
C-SDN花园GGbond1 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
Karoku0662 小时前
【网站架构部署与优化】web服务与http协议
linux·运维·服务器·数据库·http·架构
迷迭所归处2 小时前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ3 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
FreakStudio3 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
leon6253 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
锦亦之22334 小时前
QT+OSG+OSG-earth如何在窗口显示一个地球
开发语言·qt
我是苏苏4 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言