python之http模块

目录

http库结构

HTTPStatus

client

response

get请求

post请求

持久连接

server

基本使用

辅助方法

get与post

分块传输

服务端

客户端

cookies

cookie对象

服务端设置cookie

http库结构

**前言:**http标准库是python里面http的原生实现,提供了处理HTTP通信的底层基础组件。它不是一个单一的模块,而是一个包含多个子模块的包,分别负责HTTP协议的不同方面。与第三方库(如:requests)相比,HTTP库更接近协议本身,能让你深入理解HTTP的工作原理。

**注意:**使用时先导入http库(import http)

HTTPStatus

**常见状态码:**成功的话一般都是200-300,失败的话一般都是400-500

cpp 复制代码
from http import HTTPStatus
#状态
print(HTTPStatus.OK)    # 200
#状态值
print(HTTPStatus.NOT_FOUND.value)   #404
#状态码短语
print(HTTPStatus.NOT_FOUND.phrase)  #Not Found
#状态码名字
print(HTTPStatus.NOT_FOUND.name)    #NOT_FOUND
#状态码详细描述
print(HTTPStatus.NOT_FOUND.description) #Nothing matches the given URI
#通过数值来获取状态码对象
status_obj=HTTPStatus(403)
print(status_obj.name)   #FORBIDDEN

client

**前言:**该客户端是实现了http1.1协议的客户端,其支持持久连接,分块传输,https特性。

导入client: from http import client

**创建客户端http连接:**连接=client.HTTPConnection("url地址",timeout=超时整数)

**创建客户端https连接:**连接=client.HTTPSConnection("url地址",timeout=超时整数)

**创建请求:**连接.request("请求类型","请求url后路径",headers={"key":"value"})

**获取响应:**响应=连接.getresponse()

**关闭连接:**连接.close()

注意:

  • 创建连接的timeout参数是可选的,创建请求的headers是可选的
  • 创建http和https连接最后获取到的连接的使用几乎是一样的

response

cpp 复制代码
#获取响应状态码
print(response.status)  #200
#获取响应内容
print(response.reason)  #OK
# 获取单个响应头
print(response.getheader("Content-Length")) #17143
#查看是否分块传输
print(response.chunked) #False
#获取响应体
print(response.read().decode("utf-8"))

get请求

**请求:**连接.request("请求类型","请求url后路径",headers={"key":"value"})

cpp 复制代码
from http import client
#创建客户端http连接(timeout可选)
coon=client.HTTPConnection("www.baidu.com",timeout=10)
# 创建get请求(第一个)
coon.request("GET","/")
response=coon.getresponse()
#获取全部响应头
for k,v in response.getheaders():
    print(f"{k}={v}")   #太多了不打印了
#获取响应体
body=response.read()
#对响应体解码
print(body.decode("utf-8")) #太多了
#关闭连接
coon.close()

**注意:**get请求的请求参数是拼接在url上的,上面代码没显示。

post请求

**请求:**连接.request("请求类型","请求url后路径",body="json内容",headers="请求头")

cpp 复制代码
from http import client
import json
#创建客户端https连接(这次用https实验,且不加timeout)
coon=client.HTTPSConnection("www.httpbin.org")
json_data={
    "name":"python",
    "version":"3.11.4",
}
#将字典转字符串
json_body=json.dumps(json_data)
json_headers={
    "Content-type":"application/json",
    "Content-Length":str(len(json_body))
}
#其实不把请求头传入也可
coon.request("POST","/post",body=json_body,headers=json_headers)
response=coon.getresponse()
#打印响应体
print(response.read().decode("utf-8"))  #太多了
#关闭连接
coon.close()

持久连接

**查看连接状态:**状态=连接.sock

cpp 复制代码
import http
from http import client
#持久连接
coon=client.HTTPSConnection("www.httpbin.org")
#第一次请求
coon.request("GET","/get?request=1")
request_1=coon.getresponse()
print(f"request_1的请求状态为:{request_1.status}")
# request_1的请求状态为:200
#必须得把第一次请求的结果拿了才能发送第二次请求
request_1.read()
#第二次请求
coon.request("GET","/get?request=2")
request_2=coon.getresponse()
print(f"request_2的请求状态为:{request_2.status}")
# request_2的请求状态为:200
request_2.read()
#查看TCP的连接状态
print(f"连接状态为:{coon.sock}")
# 连接状态为:一堆内容
coon.close()
print(f"连接状态为:{coon.sock}")
# 连接状态为:None

server

基本使用

cpp 复制代码
import http
from http import server
class MyRequestHandler(server.BaseHTTPRequestHandler):
    #处理get请求
    def do_GET(self):
        #设置响应状态码
        self.send_response(http.HTTPStatus.OK)
        #设置响应头
        self.send_header("Content-Type","text/html;charset=utf-8")
        #结束设置响应头
        self.end_headers()
        #发送响应体
        self.wfile.write("<h1>发送的内容</h1>".encode("utf-8"))
        #确保立即发送
        self.wfile.flush()
#创建服务器实例(监听来自所有网卡访问的8080端口)
server.HTTPServer(("0.0.0.0",8080),MyRequestHandler).serve_forever()
# serve_forever()的方法是让服务器永久运行

辅助方法

**前言:**该辅助方法用于json处理。

cpp 复制代码
    #发送json数据(自定义的辅助方法)
    def sed_json(self,data,status_code=http.HTTPStatus.OK):
        self.send_response(status_code)
        self.send_header("Content-Type","application/json; charset=utf-8")
        self.end_headers()
        #ensure_ascii=False不进行ASCII码,indent为指定缩进间距
        self.wfile.write(json.dumps(data,ensure_ascii=False,indent=2).encode("utf-8"))
    #接收json数据(自定义的辅助方法)
    def get_json_body(self):
        #获取请求头对应的值
        content_length=int(self.headers.get("content-Length",0))
        if content_length==0:
            return None
        #获取对应长度的请求体
        body=self.rfile.read(content_length)
        return json.loads(body.decode("utf-8"))

**self.headers.get("content-Length",0):**去请求头(self.headers)里找 "content-Length" 这个字段,如果找到了,就返回它的值;如果没找到,就返回 0。

get与post

cpp 复制代码
from http import server
#新建http类
class APIServerHandler(server.BaseHTTPRequestHandler):
    #get方法
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.end_headers()
        #判断用户请求的是不是根路径
        if self.path=="/":
            self.wfile.write("<h1>欢迎你</h1>".encode("utf-8"))
        else:
            self.wfile.write("<h1>请访问特定页面</h1>".encode("utf-8"))
    #post方法
    def do_POST(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.end_headers()
        if self.path=="/api/users":
            content_length = int(self.headers.get("content-Length", 0))
            if content_length == 0:
                return None
            # 获取对应长度的请求体
            user_data = self.rfile.read(content_length)
            self.wfile.write(f"<h1>处理结束:{user_data}</h1>".encode("utf-8"))
        else:
            self.wfile.write("<h1>请访问特定页面</h1>".encode("utf-8"))
server=server.HTTPServer(("0.0.0.0",8000),APIServerHandler)
#永久启动
server.serve_forever()

分块传输

**前言:**服务端设置分块传输,核心是让响应头带有 Transfer-Encoding: chunked,并让响应体以流式方式逐块产出。

服务端

cpp 复制代码
from http import server
class Handler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        #设置分块传输
        self.send_header('Transfer-Encoding', 'chunked')
        self.send_header('Content-Type', 'text/plain; charset=utf-8')
        self.end_headers()
        #分块流式产出
        for i in range(5):
            text = f"这是第 {i + 1} 块数据\n"
            data = text.encode('utf-8')
            # 关键:长度必须用十六进制(:x)
            self.wfile.write(f"{len(data):x}\r\n".encode())
            self.wfile.write(data + b"\r\n")
            self.wfile.flush()  # 确保立即发送
        # 必须发送结束块,否则客户端会一直挂起等待
        self.wfile.write(b"0\r\n\r\n")
        self.wfile.flush()
server.HTTPServer(("0.0.0.0",8080),Handler).serve_forever()

注意:

  • 块长度的数字必须是十六进制。如果长度是10要写成 a而不是 10。否则客户端(如Postman)会一直等待,导致超时。
  • 每个数据块的结构必须是:十六进制长度\r\n + 数据\r\n,最后必须发送一个0\r\n\r\n作为结束标志。

客户端

cpp 复制代码
from http import client
#创建连接
coon=client.HTTPConnection("127.0.0.1:8080")
#这个端点会返回分块数据
coon.request("GET","/")
response=coon.getresponse()
print(f"查看响应状态:{response.status}")
# 查看响应状态:200
print(f"是否分块传输:{response.chunked}")
# 是否分块传输:True
while True:
    #逐步获取分块数据,每块1024字节
    chunk=response.read(1024)
    if not chunk:
        break
    print(f"收到块:{chunk.decode('utf-8').strip()}")
coon.close()

cookies

**前言:**HTTP协议是无状态的,无状态也就意味着任意两次请求之间是没有任何联系的。后来HTTP协议加入了cookie这个概念,让服务器给所有客户端都发放一个临时身份卡并保存在用户的浏览器。之后客户端每一次发送HTTP请求都会带上这张身份卡,于是服务器就能区分开不同的客户端了。

**方法:**cookie对象=cookies.SimpleCookie("已经设置好的cookie头")

cpp 复制代码
from http import cookies
cookie_header="user_id=456;username=python"
#解析
parsed_cookie=cookies.SimpleCookie(cookie_header)
#获取user_id
print(parsed_cookie["user_id"].output())
# Set-Cookie: user_id=456

注意:

  • cookie头为可选参数,作用一为初始化cookie,作用二为cookie解析
  • Cookie的本质就是服务端通过响应报文的首部set cookie进而让客户端临时保存一些数据。

cookie对象

cpp 复制代码
from http import cookies
#创建cookie管理对象
cookie=cookies.SimpleCookie()
#设置cookie
cookie["user_id"]="123"
cookie["username"]="python"
#设置复合cookie
#设置cookie过期时间为2026年5月19日
cookie["user_id"]["expires"]="19.5 2026"
cookie["user_id"]["path"]="/"

#输出所有cookie
output=cookie.output()
print(output)
# Set-Cookie: user_id=123; expires=19.5 2026; Path=/
# Set-Cookie: username=python
#输出特定cookie
print(cookie["username"].output())
# Set-Cookie: username=python
print(cookie["user_id"].output())
# Set-Cookie: user_id=123; expires=19.5 2026; Path=/
# print(cookie["user_id"]["path"].output())书写是错的
#标准输出
print(cookie["user_id"].OutputString())
# user_id=123; expires=19.5 2026; Path=/

**注意:**设置cookie时,复合cookie第一个参数只能有一种,他作为id而存在(2种就会报错)

服务端设置cookie

cpp 复制代码
import http
from http import server
from http import cookies
class MyRequestHandler(server.BaseHTTPRequestHandler):
    #处理get请求
    def do_GET(self):
        #设置响应状态码
        self.send_response(http.HTTPStatus.OK)
        #设置响应头
        self.send_header("Content-Type","text/html;charset=utf-8")
        #通用方法通过响应头给浏览器设置cookie
        self.send_header("Set-Cookie", "username=lili;user_id=456")
        #使用cookies模块来设置
        cookie=cookies.SimpleCookie()
        cookie["user_id"]="12345"
        cookie["user_id"]["max-age"]="3600"
        self.send_header("Set-Cookie",cookie["user_id"].OutputString())
        #结束设置响应头
        self.end_headers()
        #发送响应体
        self.wfile.write("<h1>已给你设置cookie</h1>".encode("utf-8"))
#创建服务器实例(监听来自所有网卡访问的8080端口)
server.HTTPServer(("0.0.0.0",8080),MyRequestHandler).serve_forever()
# serve_forever()的方法是让服务器永久运行
相关推荐
hudd66826 分钟前
JavaEE 初阶 - 网络编程(第二部分:网络编程套接字)
java·开发语言·网络·java-ee
z2014z43 分钟前
信息安全工程师 第8章 防火墙技术原理与应用 笔记
网络·php·apache
蔚蓝忧郁1 小时前
Matter DCL(分布式合规账本)
网络
Vex2une1 小时前
局域网文件共享与网络打印机共享设置:0x80070035找不到网络路径解决
网络·文件共享·局域网·打印机共享·0x80070035·找不到网络·ipconfig
蔚蓝忧郁1 小时前
Matter 协议
网络
火云代理10 小时前
动态IP是什么及其应用场景
服务器·网络·tcp/ip·动态代理ip·代理ip·火云代理·静态代理ip
迪康coolmu10 小时前
基于迪康端点安全一体化管理系统的屏幕录像审计:录屏的留存、回放与取证链
运维·服务器·网络·经验分享·安全·网络安全·制造
奇牙coding10 小时前
Grok 4.20 一直报 HTTP 401 怎么办?换了密钥还没好,可能是请求发错了入口
网络·网络协议·http·ai
约书亚的博客14 小时前
AI 主动攻击网络与计算机设备的真实案例整理
网络·人工智能