当前位置: 首页 > news >正文

Python面试题:如何在 Python 中发送 HTTP 请求?

在 Python 中发送 HTTP 请求可以使用多个库,其中最常用的是 requests 库。这个库非常直观和易于使用,支持多种 HTTP 方法,如 GET、POST、PUT、DELETE 等。以下是如何使用 requests 库发送 HTTP 请求的一些示例:

安装 requests

在使用 requests 库之前,需要先安装它。你可以使用 pip 安装:

pip install requests

发送 HTTP 请求的示例

1. 发送 GET 请求

GET 请求用于从服务器获取数据。

import requestsresponse = requests.get('https://api.example.com/data')
print(response.status_code)  # 输出状态码
print(response.text)  # 输出响应内容
2. 发送 POST 请求

POST 请求用于向服务器发送数据。

import requestsdata = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/submit', data=data)
print(response.status_code)
print(response.json())  # 如果响应内容是 JSON 格式
3. 发送带有头部信息的请求

可以在请求中添加头部信息。

import requestsheaders = {'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 中添加查询参数。

import requestsparams = {'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 响应。

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 请求上传文件。

import requestsfiles = {'file': open('report.csv', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
print(response.status_code)
print(response.text)
7. 超时设置

在请求中设置超时时间,以防止请求无限期挂起。

import requeststry: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. 处理异常

处理可能发生的请求异常。

import requeststry: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 请求。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 复合机器人:手脚眼脑的完美结合
  • 一文了解java中Optional
  • Quartz 核心
  • 在误装Windows server2019 后如何利用Windows.old恢复?
  • Python面试题:如何在 Python 中进行正则表达式操作?
  • C++笔试真题
  • FFmpeg 初级操作—打印日志,文件目录操作
  • 数学基础 -- 函数的连续性
  • 帕金森患者营养小贴士
  • 昇思25天学习打卡营第17天|SSD目标检测
  • Apache AGE 安装部署
  • 如何在 SwiftUI 中开发定制 MapKit 功能
  • 如何在 Windows 10 上恢复未保存的 Word 文档
  • 机器学习——关于极大似然估计法的一些个人思考
  • unity使用 MQTT复现plant simulate仿真
  • [分享]iOS开发 - 实现UITableView Plain SectionView和table不停留一起滑动
  • 《用数据讲故事》作者Cole N. Knaflic:消除一切无效的图表
  • 3.7、@ResponseBody 和 @RestController
  • Cumulo 的 ClojureScript 模块已经成型
  • Java 23种设计模式 之单例模式 7种实现方式
  • java8 Stream Pipelines 浅析
  • leetcode388. Longest Absolute File Path
  • niucms就是以城市为分割单位,在上面 小区/乡村/同城论坛+58+团购
  • Node.js 新计划:使用 V8 snapshot 将启动速度提升 8 倍
  • PhantomJS 安装
  • Vue全家桶实现一个Web App
  • Vue--数据传输
  • 给自己的博客网站加上酷炫的初音未来音乐游戏?
  • 工作中总结前端开发流程--vue项目
  • 力扣(LeetCode)21
  • 前言-如何学习区块链
  • 入口文件开始,分析Vue源码实现
  • 三栏布局总结
  • 山寨一个 Promise
  • 试着探索高并发下的系统架构面貌
  • 无服务器化是企业 IT 架构的未来吗?
  • 延迟脚本的方式
  • 译自由幺半群
  • 看到一个关于网页设计的文章分享过来!大家看看!
  • 阿里云服务器如何修改远程端口?
  • #if和#ifdef区别
  • #每天一道面试题# 什么是MySQL的回表查询
  • #使用清华镜像源 安装/更新 指定版本tensorflow
  • (13)Latex:基于ΤΕΧ的自动排版系统——写论文必备
  • (C++二叉树05) 合并二叉树 二叉搜索树中的搜索 验证二叉搜索树
  • (C语言)二分查找 超详细
  • (Oracle)SQL优化技巧(一):分页查询
  • (超详细)2-YOLOV5改进-添加SimAM注意力机制
  • (顶刊)一个基于分类代理模型的超多目标优化算法
  • (附源码)php投票系统 毕业设计 121500
  • (免费分享)基于springboot,vue疗养中心管理系统
  • (十二)springboot实战——SSE服务推送事件案例实现
  • (四)Linux Shell编程——输入输出重定向
  • (一)为什么要选择C++
  • .[hudsonL@cock.li].mkp勒索病毒数据怎么处理|数据解密恢复