01- web应用与https协议

本文介绍了如何使用Python的socket模块搭建简易的HTTP服务器,并演示了GET与POST两种请求方式的具体实现过程。此外,还详细解释了HTTP请求与响应的基本格式。

1、

 

import socket


server = socket.socket()
server.bind(("127.0.0.1", 8800))
server.listen(5)

while True:
    print('server is waiting...')
    conn, addr = server.accept()
    data = conn.recv(1024)
    print('data:', data)
    # conn.send(b'hello luffycity')
    conn.send(b'HTTP/1.1 200 OK\r\n\r\nhello luffycity')  # 添加http响应头
    conn.close()

 

2

  

import socket


server = socket.socket()
server.bind(("127.0.0.1", 8800))
server.listen(5)

while True:
    print('server is waiting...')
    conn, addr = server.accept()
    data = conn.recv(1024)
    print('data:', data)

    # 读取html文件
    with open('index.html', 'r') as f:
        data = f.read()
        
    # 响应报头 + data
    conn.send(('HTTP/1.1 200 OK\r\n\r\n%s' % data).encode('utf8'))
    conn.close()

 

 

 3.http请求协议

 请求格式

 

 

get方式

GET / HTTP/1.1\r\n
Host: 127.0.0.1:8800\r\n
Connection: keep-alive\r\n
Pragma: no-cache\r\n
Cache-Control: no-cache\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n\r\n

请求首行\r\n
请求头\r\n
请求头\r\n
请求头\r\n
请求头\r\n
...\r\n\r\n

 

post方式

login.html 登录form表单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8800" method="post">
    username: <input type="text" name="useranme">
    password: <input type="password" name="password">
    <input type="submit">
</form>
</body>
</html>

 

POST / HTTP/1.1\r\n
Host: 127.0.0.1:8800\r\n
Connection: keep-alive\r\n
Content-Length: 26\r\n
Pragma: no-cache\r\n
Cache-Control: no-cache\r\n
Origin: http://127.0.0.1:8800\r\n
Upgrade-Insecure-Requests: 1\r\n
Content-Type: application/x-www-form-urlencoded\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Referer: http://127.0.0.1:8800/\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n\r\n

useranme=jack&password=2222'

 

请求首行\r\n
请求头\r\n
请求头\r\n
请求头\r\n
请求头\r\n
...\r\n\r\n

请求体(a=1&b=2) # 注意只有post请求才会有请求体

 

 

 

 

 区别

 

 

 

3、响应协议

   # 响应格式 + data
    conn.send(('HTTP/1.1 200 OK\r\nContent-Type:text/html\r\n\r\n%s' % data).encode('utf8'))
   

 

 响应码状态

 

4

 

转载于:https://www.cnblogs.com/venicid/p/9227887.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值