Python发送HTTP请求最推荐使用requests库,它封装了GET、POST、认证、会话管理等操作,API简洁易用。首先安装:pip install requests。发送GET请求获取数据:import requests; response = requests.get('https://api.github.com/events'); print(response.status_code, response.json()[:3])。发送POST请求提交数据:requests.post('https://httpbin.org/post', json={'name': '张三', 'age': 30})。带参数的GET请求使用params:requests.get('https://api.github.com/search/repositories', params={'q': 'requests+language:python'})。需认证时可用auth=('user', 'passwd')进行基本认证。保持会话应使用Session对象:session = requests.Session(); session.get(login_url); session.get(protected_url)自动携带Cookie。高级功能包括文件上传:files = {'upload_file': open('example.txt', 'rb')}; requests.post(url, files=files)。自定义请求头:headers = {'User-Agent': 'MyApp'}; requests.get(url, headers=headers)。控制重定向:allow_redirects=False可禁用自动跳转。设置超时避免阻塞:timeout=(1, 3)。常见错误有ConnectionError、Timeout、HTTPError、SSLError和JSONDecodeError,应使用try-except捕获requests.exceptions.RequestException基类。调试时检查response.status_code、

Python要发送HTTP请求,最常用也最推荐的方式是使用
requests
urllib.request
requests
Python发送HTTP请求的核心,其实就是与服务器进行数据交换。这听起来有点抽象,但本质上就是你的程序像浏览器一样,向某个网址发出一个“请求”,然后等待服务器给你一个“回应”。最常见的请求类型是GET和POST。GET请求通常用于获取数据,比如你访问一个网页;POST请求则用于提交数据,比如你填写表单并点击提交。
我个人在工作中,几乎离不开
requests
使用
requests
pip install requests
立即学习“Python免费学习笔记(深入)”;
发送GET请求
这是最简单的请求类型,通常用于从服务器获取信息。
import requests
try:
# 尝试获取一个公开的API数据
response = requests.get('https://api.github.com/events')
response.raise_for_status() # 如果状态码不是200,则抛出HTTPError异常
print(f"状态码: {response.status_code}")
print(f"响应头: {response.headers['Content-Type']}")
# 打印前几个JSON对象,避免输出过长
print("响应内容 (部分):")
for item in response.json()[:3]:
print(item.get('id'), item.get('type'))
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")这里我们向GitHub的公开API发送了一个GET请求。
response.raise_for_status()
response.json()
发送POST请求
POST请求通常用于向服务器提交数据,比如创建新资源或者发送表单数据。
import requests
import json
url = 'https://httpbin.org/post' # 一个测试POST请求的网站
payload = {'name': '张三', 'age': 30}
headers = {'Content-Type': 'application/json'} # 明确告诉服务器发送的是JSON数据
try:
# 发送JSON数据
response = requests.post(url, data=json.dumps(payload), headers=headers)
response.raise_for_status()
print(f"状态码: {response.status_code}")
print("服务器响应:")
print(response.json())
# 也可以直接通过json参数发送字典,requests会自动处理序列化和Content-Type
response_json_param = requests.post(url, json=payload)
response_json_param.raise_for_status()
print("\n使用json参数发送:")
print(response_json_param.json())
except requests.exceptions.RequestException as e:
print(f"POST请求失败: {e}")在POST请求中,
data
json
requests
Content-Type
处理查询参数
GET请求经常需要带上查询参数,
requests
params
import requests
url = 'https://api.github.com/search/repositories'
params = {'q': 'requests+language:python', 'sort': 'stars', 'order': 'desc'}
try:
response = requests.get(url, params=params)
response.raise_for_status()
print(f"搜索Python requests库,星标最多的结果 (部分):")
for repo in response.json()['items'][:2]:
print(f"- {repo['full_name']} (Stars: {repo['stargazers_count']})")
except requests.exceptions.RequestException as e:
print(f"带参数的GET请求失败: {e}")requests
params
在实际开发中,很多API都需要认证才能访问,而且我们经常需要保持与服务器的会话(session),比如登录后保持登录状态。
requests
基本认证 (Basic Authentication)
对于一些简单的API,可能只需要用户名和密码进行基本认证。
import requests
# 假设有一个需要基本认证的API
url = 'https://httpbin.org/basic-auth/user/passwd'
auth_tuple = ('user', 'passwd') # 用户名和密码
try:
response = requests.get(url, auth=auth_tuple)
response.raise_for_status()
print(f"基本认证状态码: {response.status_code}")
print(f"认证结果: {response.json()}")
except requests.exceptions.RequestException as e:
print(f"基本认证请求失败: {e}")auth
(username, password)
requests
会话管理 (Session)
当你需要跨多个请求保持某些状态(如cookies、自定义请求头)时,使用
Session
import requests
# 创建一个Session对象
session = requests.Session()
# 模拟登录(假设登录成功后服务器会设置cookie)
login_url = 'https://httpbin.org/cookies/set/sessioncookie/12345'
session.get(login_url) # 这一步会设置一个cookie到session对象中
print(f"Session中当前的Cookie: {session.cookies.get('sessioncookie')}")
# 接下来,所有通过这个session对象发送的请求都会自动带上之前获取的cookie
protected_resource_url = 'https://httpbin.org/cookies'
response = session.get(protected_resource_url)
response.raise_for_status()
print(f"访问受保护资源时的Cookie: {response.json().get('cookies')}")
# 你也可以给session设置默认的请求头
session.headers.update({'User-Agent': 'MyCustomApp/1.0'})
response_with_custom_ua = session.get('https://httpbin.org/headers')
print(f"使用自定义User-Agent: {response_with_custom_ua.json().get('headers').get('User-Agent')}")
session.close() # 使用完毕后记得关闭session,释放资源Session
Session
除了基本的GET和POST,HTTP请求还有很多高级的玩法,比如文件上传、自定义请求头、处理重定向、设置代理等。
requests
文件上传
上传文件是常见的需求,
requests
files
import requests
url = 'https://httpbin.org/post'
file_path = 'example.txt' # 假设有一个名为example.txt的文件
# 创建一个示例文件
with open(file_path, 'w') as f:
f.write('这是一个测试文件内容。\n')
f.write('用于Python requests的文件上传示例。')
try:
with open(file_path, 'rb') as f: # 注意,文件需要以二进制模式打开
files = {'upload_file': f} # 键是表单字段名,值是文件对象
response = requests.post(url, files=files)
response.raise_for_status()
print(f"文件上传状态码: {response.status_code}")
print("服务器响应 (文件部分):")
print(response.json().get('files'))
print(response.json().get('form')) # 如果有其他表单字段也会在这里
except requests.exceptions.RequestException as e:
print(f"文件上传失败: {e}")
finally:
import os
if os.path.exists(file_path):
os.remove(file_path) # 清理创建的测试文件files
自定义请求头 (Headers)
有时候,我们需要自定义请求头来模拟浏览器行为、传递认证信息或指定内容类型。
import requests
url = 'https://httpbin.org/headers'
custom_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',
'X-My-Custom-Header': 'Python-Requests-Demo'
}
try:
response = requests.get(url, headers=custom_headers)
response.raise_for_status()
print(f"自定义请求头状态码: {response.status_code}")
print("服务器接收到的头信息:")
print(response.json().get('headers'))
except requests.exceptions.RequestException as e:
print(f"自定义请求头失败: {e}")headers
requests
处理重定向 (Redirects)
HTTP请求经常会遇到3xx状态码的重定向。
requests
import requests
# 一个会重定向的URL
redirect_url = 'http://httpbin.org/redirect/3' # 会重定向3次
try:
# 默认情况下,requests会自动跟随重定向
response_auto = requests.get(redirect_url)
print(f"自动跟随重定向后的最终URL: {response_auto.url}")
print(f"自动跟随重定向后的状态码: {response_auto.status_code}")
print(f"重定向历史: {[r.url for r in response_auto.history]}")
print("\n--- 不跟随重定向 ---")
# 设置allow_redirects=False,requests就不会跟随重定向
response_no_redirect = requests.get(redirect_url, allow_redirects=False)
print(f"不跟随重定向时的URL: {response_no_redirect.url}")
print(f"不跟随重定向时的状态码: {response_no_redirect.status_code}")
print(f"不跟随重定向时的响应头: {response_no_redirect.headers.get('Location')}")
except requests.exceptions.RequestException as e:
print(f"重定向请求失败: {e}")response.history
allow_redirects=False
超时设置 (Timeouts)
网络请求可能会因为各种原因卡住,设置超时是一个非常重要的实践,避免程序无限等待。
import requests
# 一个会延迟响应的URL
delay_url = 'https://httpbin.org/delay/5' # 延迟5秒响应
try:
# 设置1秒的连接超时和3秒的读取超时
response = requests.get(delay_url, timeout=(1, 3))
print(f"超时设置后的状态码: {response.status_code}")
except requests.exceptions.ConnectTimeout:
print("连接超时!服务器在指定时间内未建立连接。")
except requests.exceptions.ReadTimeout:
print("读取超时!服务器在指定时间内未发送数据。")
except requests.exceptions.RequestException as e:
print(f"其他请求错误: {e}")timeout
(connect_timeout, read_timeout)
在发送HTTP请求时,遇到错误是家常便饭。理解这些错误类型并掌握调试技巧,能大大提高开发效率。
常见的错误类型
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))ConnectTimeout
ReadTimeout
response.raise_for_status()
response.json()
调试技巧
异常捕获 (Try-Except): 始终使用
try-except
requests.exceptions.RequestException
requests
import requests
try:
response = requests.get('http://nonexistent-domain.com')
response.raise_for_status()
except requests.exceptions.ConnectionError as e:
print(f"连接错误: {e}")
except requests.exceptions.Timeout as e:
print(f"请求超时: {e}")
except requests.exceptions.HTTPError as e:
print(f"HTTP错误: {e.response.status_code} - {e.response.text}")
except requests.exceptions.RequestException as e:
print(f"未知请求错误: {e}")检查响应对象: 当请求返回时,
response
response.status_code
response.url
response.headers
response.text
response.json()
JSONDecodeError
response.content
import requests
response = requests.get('https://httpbin.org/status/404')
print(f"状态码: {response.status_code}")
print(f"URL: {response.url}")
print(f"响应头: {response.headers}")
print(f"响应文本: {response.text}")打印请求详情: 有时候需要知道
requests
requests
curl_cffi
http.client
requests
url
params
data
headers
日志记录 (Logging): 在生产环境中,使用Python的
logging
import logging
import requests
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
try:
response = requests.get('https://api.github.com/nonexistent-endpoint')
response.raise_for_status()
logging.info(f"请求成功: {response.status_code}")
except requests.exceptions.HTTPError as e:
logging.error(f"HTTP错误: {e.response.status_code} - {e.response.text}")
except requests.exceptions.RequestException as e:
logging.error(f"请求失败: {e}")禁用SSL验证 (Verify=False): 在开发或测试环境中,如果遇到SSL证书问题,可以暂时禁用SSL验证。但请注意,这会降低安全性,不建议在生产环境中使用。
import requests
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) # 禁用警告
try:
response = requests.get('https://self-signed-cert.com', verify=False)
# ...
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")理解这些错误和调试技巧,能让你在面对各种网络请求问题时,不至于手足无措。通常,我都会从检查状态码和响应内容开始,如果还不行,再深入查看异常栈和请求参数。
以上就是Python怎么发送HTTP请求_Python HTTP请求发送实践指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号