利用request库处理HTTP

博客主要对HTTP协议进行回顾,涵盖请求类型、响应类型、Session/Cookie以及其他补充内容。这些都是信息技术中网络通信的关键知识,有助于理解HTTP协议在网络交互中的工作机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、HTTP协议回顾

1.请求类型

 2.响应类型

3.Session/Cookie

4.其它补充


一、HTTP协议回顾

1.请求类型

 2.响应类型

3.Session/Cookie

 

 

4.其它补充

 

import requests

# 发送GET请求
resp = requests.get('http://localhost:8080/woniusales/')
resp.encoding = 'utf-8'     # 设置编码格式
print(resp.text)            # 打印响应正文

# 发送POST请求
data = {'username':'admin', 'password':'admin123', 'verifycode':'0000'}
resp = requests.post(url='http://localhost:8080/woniusales/user/login', data=data)
print(resp.text)
print(resp.headers)         # 打印响应头
if resp.text == 'login-pass':       # 对响应进行判断
    print("登录成功")
else:
    print("登录失败")

# 登录成功后获取响应的Cookie,用于在后续请求中使用
cookie = resp.cookies

# 下载图片
url = 'http://old.woniuxy.com/page/img/banner/class_time_home.png'
resp = requests.get(url)
with open('./banner.jpg', mode='wb') as file:
    file.write(resp.content)

# 文件上传
file = {'batchfile': open('E:/Other/SaleList-20171020-Test.xls', 'rb')}
data = {'batchname': 'GB20211009'}
resp = requests.post(url='http://localhost:8080/woniusales/goods/upload', data=data, files=file, cookies=cookie)
print(resp.text)

#
# # 第二种维持Session的用法(推荐)
session = requests.session()
data = {'username':'admin', 'password':'admin123', 'verifycode':'0000'}
resp = session.post(url='http://localhost:8080/woniusales/user/login', data=data)

file = {'batchfile': open('E:/Other/SaleList-20171020-Test.xls', 'rb')}
data = {'batchname': 'GB20211007'}
resp = session.post(url='http://localhost:8080/woniusales/goods/upload', data=data, files=file)
print(resp.text)
print(type(resp.text))

# # 利用Python直接处理JSON
import json
list = json.loads(resp.text)    # 将字符串反序列化成List+Dict的Python对象 序列化是dump
print(list)
print(type(list))
print(list[1]['goodsname'])     # 输出字典的某个值
#
#
# # 处理HTTPS请求
resp = requests.get('https://www.woniuxy.cn', verify=False)     # 忽略证书
print(resp.text)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值