requests库是Python发送HTTP请求的首选工具,其核心在于使用get()和post()方法处理不同场景。GET用于获取数据,参数通过URL传递,适合幂等性查询;POST用于提交数据,信息置于请求体中,适合传输敏感或大量数据。实际应用中,根据是否改变服务器状态来选择:获取资源用GET,创建或更新用POST。处理JSON时,可直接使用json参数自动序列化并设置Content-Type;文件上传则通过files参数支持多部分表单,需以二进制模式打开文件。为提升健壮性,应使用try-except捕获Timeout、ConnectionError等异常,合理设置timeout防止阻塞,并可控制allow_redirects参数管理重定向行为。这些机制共同确保了网络交互的可靠性与安全性。

Python中,要发送HTTP请求,
requests
使用
requests
requests.get()
requests.post()
比如,发送一个GET请求获取网页内容:
import requests
try:
response = requests.get('https://www.example.com')
# 检查响应状态码,200表示成功
if response.status_code == 200:
print("请求成功!")
print("响应内容类型:", response.headers['Content-Type'])
print("响应内容预览:", response.text[:200]) # 打印前200个字符
else:
print(f"请求失败,状态码: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"请求发生错误: {e}")发送POST请求时,通常需要传递数据,这可以通过
data
json
立即学习“Python免费学习笔记(深入)”;
import requests
import json
# 发送表单数据
payload_data = {'key1': 'value1', 'key2': 'value2'}
try:
response_form = requests.post('https://httpbin.org/post', data=payload_data)
print("\nPOST表单数据响应:")
print(response_form.json())
except requests.exceptions.RequestException as e:
print(f"POST表单数据请求发生错误: {e}")
# 发送JSON数据
payload_json = {'name': 'Alice', 'age': 30}
try:
response_json = requests.post('https://httpbin.org/post', json=payload_json)
print("\nPOST JSON数据响应:")
print(response_json.json())
except requests.exceptions.RequestException as e:
print(f"POST JSON数据请求发生错误: {e}")我们还可以通过
headers
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
}
try:
response_with_headers = requests.get('https://www.example.com', headers=headers)
print("\n带自定义头的GET请求成功!")
print("响应状态码:", response_with_headers.status_code)
except requests.exceptions.RequestException as e:
print(f"带自定义头的GET请求发生错误: {e}")这些只是冰山一角,但足以展示
requests
在HTTP请求的世界里,GET和POST无疑是最常用的两种方法,但它们的设计哲学和适用场景却大相径庭。选择哪一个,往往取决于你的意图和数据的性质。
简单来说,GET请求就像是“查询”或“获取”资源。它的特点是参数会附加在URL的末尾,形成查询字符串(Query String),例如
example.com/search?query=python&page=1
而POST请求则更像是“提交”或“创建”资源。它的数据是放在请求体(Request Body)中发送的,而不是URL里。这意味着POST可以传输大量数据,数据在URL中不可见(虽然也不是绝对安全,仍然可能被截获),更适合传输敏感信息,比如用户登录凭证。POST请求通常用于向服务器提交表单数据、上传文件、创建新资源等操作。与GET不同,POST请求是非幂等的,重复发送可能会导致创建多个相同的资源(例如,多次提交订单可能会生成多个订单)。
在实际使用中,我通常会这样考虑:如果我只是想获取一个网页内容、查询一些数据,或者请求一个不需要修改服务器状态的API接口,我会毫不犹豫地选择
requests.get()
requests.post()
处理JSON数据和文件上传是
requests
处理JSON数据:
当你需要向API发送JSON格式的数据时,
requests
json
json
requests
Content-Type
application/json
import requests
api_url = 'https://api.example.com/items' # 假设这是一个接收JSON的API
new_item_data = {
'name': 'Python Requests Book',
'price': 49.99,
'tags': ['programming', 'web', 'python']
}
try:
response = requests.post(api_url, json=new_item_data)
response.raise_for_status() # 如果请求失败(状态码非2xx),抛出HTTPError异常
print("新项目创建成功!")
print(response.json()) # API通常会返回创建成功的资源信息
except requests.exceptions.HTTPError as errh:
print(f"HTTP错误: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"连接错误: {errc}")
except requests.exceptions.Timeout as errt:
print(f"超时错误: {errt}")
except requests.exceptions.RequestException as err:
print(f"发生未知错误: {err}")这种方式比手动
json.dumps()
headers
response.json()
json.loads()
处理文件上传:
文件上传通常通过POST请求完成,
requests
files
('filename', file_object, 'content_type', custom_headers)最常见的用法是直接传入文件路径或已打开的文件对象:
import requests
upload_url = 'https://httpbin.org/post' # 一个测试文件上传的API
# 方法一:直接传入文件路径(requests会自动打开和关闭文件)
try:
with open('my_document.txt', 'w') as f:
f.write("This is a test document for upload.")
files = {'file_field_name': open('my_document.txt', 'rb')}
response_upload = requests.post(upload_url, files=files)
response_upload.raise_for_status()
print("\n文件上传成功 (方法一)!")
print(response_upload.json()['files'])
files['file_field_name'].close() # 手动关闭文件,或者使用with语句
except FileNotFoundError:
print("文件 'my_document.txt' 不存在。")
except requests.exceptions.RequestException as e:
print(f"文件上传发生错误: {e}")
# 方法二:更灵活的方式,指定文件名和内容类型
try:
file_content = b"This is another file content."
files_flex = {
'another_file_field': ('report.pdf', file_content, 'application/pdf', {'Expires': '0'})
}
response_upload_flex = requests.post(upload_url, files=files_flex)
response_upload_flex.raise_for_status()
print("\n文件上传成功 (方法二)!")
print(response_upload_flex.json()['files'])
except requests.exceptions.RequestException as e:
print(f"文件上传发生错误: {e}")需要注意的是,当上传二进制文件时,请确保以二进制模式(
'rb'
requests
multipart/form-data
在实际的网络请求中,错误、延迟和重定向是家常便饭。一个健壮的应用程序必须能够优雅地处理这些情况。
requests
异常处理:
网络请求失败的原因有很多,可能是网络断开、服务器无响应、DNS解析失败,甚至是请求超时。
requests
requests.exceptions.RequestException
try...except
import requests
try:
response = requests.get('http://nonexistent-domain-12345.com', timeout=5) # 故意请求一个不存在的域名
response.raise_for_status() # 如果状态码不是200,抛出HTTPError
print("请求成功!")
except requests.exceptions.Timeout:
print("请求超时,服务器长时间未响应。")
except requests.exceptions.ConnectionError:
print("连接错误,可能网络有问题或服务器不可达。")
except requests.exceptions.HTTPError as e:
print(f"HTTP错误,状态码: {e.response.status_code}")
except requests.exceptions.RequestException as e:
print(f"发生未知请求错误: {e}")通过捕获更具体的异常(如
Timeout
ConnectionError
HTTPError
超时设置:
网络延迟是不可避免的,如果一个请求长时间没有响应,可能会阻塞程序的执行。
requests
Timeout
import requests
try:
# 设置连接超时为3秒,读取超时为5秒
response = requests.get('https://www.google.com', timeout=(3, 5))
print("请求成功,未超时。")
except requests.exceptions.Timeout:
print("请求超时!")
except requests.exceptions.RequestException as e:
print(f"请求发生错误: {e}")
# timeout也可以是一个浮点数,表示总的超时时间
try:
response = requests.get('https://www.example.com', timeout=10.5)
print("请求成功,未超时。")
except requests.exceptions.Timeout:
print("请求超时!")
except requests.exceptions.RequestException as e:
print(f"请求发生错误: {e}")合理设置超时时间可以防止程序因为等待一个无响应的服务器而无限期阻塞,这对于构建可靠的系统非常重要。
重定向处理:
当访问一个URL时,服务器有时会返回一个重定向响应(例如301永久移动,302临时移动),指示客户端去访问另一个URL。
requests
import requests
# 访问一个会重定向的URL,例如 httpbin.org/redirect/3 会重定向3次
response = requests.get('https://httpbin.org/redirect/3')
print(f"最终URL: {response.url}")
print(f"重定向历史: {response.history}") # 包含了所有重定向的响应对象如果你不希望
requests
allow_redirects
False
import requests
response_no_redirect = requests.get('https://httpbin.org/redirect/1', allow_redirects=False)
print(f"不跟随重定向时的状态码: {response_no_redirect.status_code}") # 应该是302或301
print(f"不跟随重定向时的URL: {response_no_redirect.url}") # 仍然是原始URL通过灵活运用这些机制,我们可以更好地控制请求行为,处理各种网络不确定性,从而构建出更加健壮和可靠的Python应用程序。在我的开发经验中,恰当的异常处理和超时设置,往往能避免很多难以追踪的生产问题。
以上就是python中如何使用requests库发送HTTP请求_Python requests库HTTP请求发送指南的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号