实例1:HTTP请求与响应的基本结构
在开始深入HTTP协议网络编程之前,我们先来了解一下HTTP请求与响应的基本结构。HTTP请求通常由请求行、请求头和请求体组成,而HTTP响应则由状态行、响应头和响应体组成。
# 示例:HTTP请求
GET /index.html HTTP/1.1
Host: www.example.com
Connection: keep-alive
# 示例:HTTP响应
HTTP/1.1 200 OK
Server: Apache/2.4.7 (Ubuntu)
Content-Type: text/html
Content-Length: 1024
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Welcome to Example</h1>
</body>
</html>
实例2:GET与POST请求的区别
GET请求用于请求数据,而POST请求用于提交数据。在GET请求中,数据通常附加在URL中,而在POST请求中,数据则放在请求体中。
# 示例:GET请求
GET /search?q=example HTTP/1.1
Host: www.example.com
# 示例:POST请求
POST /submit HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
q=example&submit=Search
实例3:HTTP状态码及其含义
HTTP状态码用于表示请求的结果。常见的状态码包括200(成功)、404(未找到)、500(服务器错误)等。
# 示例:200状态码
HTTP/1.1 200 OK
Server: Apache/2.4.7 (Ubuntu)
Content-Type: text/html
Content-Length: 1024
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Welcome to Example</h1>
</body>
</html>
# 示例:404状态码
HTTP/1.1 404 Not Found
Server: Apache/2.4.7 (Ubuntu)
Content-Type: text/html
Content-Length: 1024
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Page not found</h1>
</body>
</html>
实例4:使用Python的http.client模块发送HTTP请求
Python的http.client模块提供了发送HTTP请求的功能。以下是一个简单的示例:
import http.client
# 创建连接
conn = http.client.HTTPConnection("www.example.com")
# 发送GET请求
conn.request("GET", "/index.html")
# 获取响应
response = conn.getresponse()
# 打印响应内容
print(response.read())
# 关闭连接
conn.close()
实例5:使用Python的requests库发送HTTP请求
requests库是Python中一个非常流行的HTTP库,它简化了HTTP请求的发送。以下是一个简单的示例:
import requests
# 发送GET请求
response = requests.get("http://www.example.com/index.html")
# 打印响应内容
print(response.text)
实例6:使用Python的Flask框架创建简单的HTTP服务器
Flask是一个轻量级的Web应用框架,可以方便地创建HTTP服务器。以下是一个简单的示例:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
实例7:使用Python的Django框架创建简单的HTTP服务器
Django是一个高级的Web框架,它提供了许多内置的功能。以下是一个简单的示例:
from django.http import HttpResponse
from django.views import View
class IndexView(View):
def get(self, request):
return HttpResponse('Hello, World!')
# 启动Django服务器
if __name__ == '__main__':
from django.core.management import execute_from_command_line
execute_from_command_line(['runserver', '0.0.0.0:8000'])
实例8:使用Python的Tornado框架创建简单的HTTP服务器
Tornado是一个高性能的Web服务器和异步网络库。以下是一个简单的示例:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, World!")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
实例9:使用Python的aiohttp库发送异步HTTP请求
aiohttp是一个异步HTTP客户端和服务器框架。以下是一个简单的示例:
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, "http://www.example.com/index.html")
print(html)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
实例10:使用Python的urllib库发送HTTP请求
urllib是Python标准库中的一个模块,提供了发送HTTP请求的功能。以下是一个简单的示例:
import urllib.request
# 发送GET请求
response = urllib.request.urlopen("http://www.example.com/index.html")
# 打印响应内容
print(response.read())
实例11:使用Python的http.server模块创建简单的HTTP服务器
http.server是Python标准库中的一个模块,可以用来创建简单的HTTP服务器。以下是一个简单的示例:
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
实例12:使用Python的socket库发送HTTP请求
socket是Python标准库中的一个模块,可以用来创建TCP/IP套接字。以下是一个简单的示例:
import socket
# 创建套接字
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
s.connect(("www.example.com", 80))
# 发送HTTP请求
s.sendall(b"GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n")
# 接收响应
data = b""
while True:
packet = s.recv(4096)
if not packet:
break
data += packet
# 打印响应内容
print(data.decode())
# 关闭套接字
s.close()
实例13:使用Python的requests库发送HTTPS请求
requests库也支持HTTPS请求。以下是一个简单的示例:
import requests
# 发送HTTPS请求
response = requests.get("https://www.example.com/index.html")
# 打印响应内容
print(response.text)
实例14:使用Python的urllib库发送HTTPS请求
urllib库也支持HTTPS请求。以下是一个简单的示例:
import urllib.request
# 发送HTTPS请求
response = urllib.request.urlopen("https://www.example.com/index.html")
# 打印响应内容
print(response.read())
实例15:使用Python的http.client模块发送HTTPS请求
http.client模块也支持HTTPS请求。以下是一个简单的示例:
import http.client
# 创建连接
conn = http.client.HTTPSConnection("www.example.com")
# 发送GET请求
conn.request("GET", "/index.html")
# 获取响应
response = conn.getresponse()
# 打印响应内容
print(response.read())
# 关闭连接
conn.close()
实例16:使用Python的aiohttp库发送异步HTTPS请求
aiohttp库也支持异步HTTPS请求。以下是一个简单的示例:
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, "https://www.example.com/index.html")
print(html)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
实例17:使用Python的requests库发送HTTP请求并处理响应头
requests库允许你轻松地处理响应头。以下是一个简单的示例:
import requests
# 发送GET请求
response = requests.get("http://www.example.com/index.html")
# 打印响应头
print(response.headers)
实例18:使用Python的urllib库发送HTTP请求并处理响应头
urllib库也允许你处理响应头。以下是一个简单的示例:
import urllib.request
# 发送HTTP请求
response = urllib.request.urlopen("http://www.example.com/index.html")
# 打印响应头
print(response.info())
实例19:使用Python的http.client模块发送HTTP请求并处理响应头
http.client模块也允许你处理响应头。以下是一个简单的示例:
import http.client
# 创建连接
conn = http.client.HTTPConnection("www.example.com")
# 发送GET请求
conn.request("GET", "/index.html")
# 获取响应
response = conn.getresponse()
# 打印响应头
print(response.getheaders())
# 关闭连接
conn.close()
实例20:使用Python的aiohttp库发送异步HTTP请求并处理响应头
aiohttp库也允许你处理异步HTTP请求的响应头。以下是一个简单的示例:
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return response.headers
async def main():
async with aiohttp.ClientSession() as session:
headers = await fetch(session, "http://www.example.com/index.html")
print(headers)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
实例21:使用Python的requests库发送POST请求并处理响应体
requests库允许你发送POST请求并处理响应体。以下是一个简单的示例:
import requests
# 发送POST请求
response = requests.post("http://www.example.com/submit", data={"q": "example", "submit": "Search"})
# 打印响应体
print(response.text)
实例22:使用Python的urllib库发送POST请求并处理响应体
urllib库也允许你发送POST请求并处理响应体。以下是一个简单的示例:
import urllib.request
# 发送POST请求
data = urllib.parse.urlencode({"q": "example", "submit": "Search"})
req = urllib.request.Request("http://www.example.com/submit", data=data)
# 获取响应
response = urllib.request.urlopen(req)
# 打印响应体
print(response.read())
实例23:使用Python的http.client模块发送POST请求并处理响应体
http.client模块也允许你发送POST请求并处理响应体。以下是一个简单的示例:
import http.client
# 创建连接
conn = http.client.HTTPConnection("www.example.com")
# 发送POST请求
conn.request("POST", "/submit", body="q=example&submit=Search")
# 获取响应
response = conn.getresponse()
# 打印响应体
print(response.read())
# 关闭连接
conn.close()
实例24:使用Python的aiohttp库发送异步POST请求并处理响应体
aiohttp库也允许你发送异步POST请求并处理响应体。以下是一个简单的示例:
import aiohttp
async def fetch(session, url, data):
async with session.post(url, data=data) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, "http://www.example.com/submit", {"q": "example", "submit": "Search"})
print(html)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
实例25:使用Python的requests库发送JSON数据
requests库允许你发送JSON数据。以下是一个简单的示例:
import requests
# 发送JSON数据
response = requests.post("http://www.example.com/submit", json={"q": "example", "submit": "Search"})
# 打印响应体
print(response.text)
实例26:使用Python的urllib库发送JSON数据
urllib库也允许你发送JSON数据。以下是一个简单的示例:
import urllib.request
import json
# 发送JSON数据
data = json.dumps({"q": "example", "submit": "Search"})
req = urllib.request.Request("http://www.example.com/submit", data=data.encode(), headers={'Content-Type': 'application/json'})
# 获取响应
response = urllib.request.urlopen(req)
# 打印响应体
print(response.read())
实例27:使用Python的http.client模块发送JSON数据
http.client模块也允许你发送JSON数据。以下是一个简单的示例:
import http.client
import json
# 创建连接
conn = http.client.HTTPConnection("www.example.com")
# 发送JSON数据
conn.request("POST", "/submit", body=json.dumps({"q": "example", "submit": "Search"}), headers={'Content-Type': 'application/json'})
# 获取响应
response = conn.getresponse()
# 打印响应体
print(response.read())
# 关闭连接
conn.close()
实例28:使用Python的aiohttp库发送异步JSON数据
aiohttp库也允许你发送异步JSON数据。以下是一个简单的示例:
import aiohttp
import json
async def fetch(session, url, data):
async with session.post(url, json=data) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, "http://www.example.com/submit", {"q": "example", "submit": "Search"})
print(html)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
实例29:使用Python的requests库发送表单数据
requests库允许你发送表单数据。以下是一个简单的示例:
import requests
# 发送表单数据
response = requests.post("http://www.example.com/submit", data={"q": "example", "submit": "Search"})
# 打印响应体
print(response.text)
实例30:使用Python的urllib库发送表单数据
urllib库也允许你发送表单数据。以下是一个简单的示例:
import urllib.request
import urllib.parse
# 发送表单数据
data = urllib.parse.urlencode({"q": "example", "submit": "Search"})
req = urllib.request.Request("http://www.example.com/submit", data=data)
# 获取响应
response = urllib.request.urlopen(req)
# 打印响应体
print(response.read())
实例31:使用Python的http.client模块发送表单数据
http.client模块也允许你发送表单数据。以下是一个简单的示例:
import http.client
import urllib.parse
# 创建连接
conn = http.client.HTTPConnection("www.example.com")
# 发送表单数据
conn.request("POST", "/submit", body=urllib.parse.urlencode({"q": "example", "submit": "Search"}))
# 获取响应
response = conn.getresponse()
# 打印响应体
print(response.read())
# 关闭连接
conn.close()
实例32:使用Python的aiohttp库发送异步表单数据
aiohttp库也允许你发送异步表单数据。以下是一个简单的示例:
import aiohttp
import urllib.parse
async def fetch(session, url, data):
async with session.post(url, data=data) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, "http://www.example.com/submit", {"q": "example", "submit": "Search"})
print(html)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
实例33:使用Python的requests库发送文件
requests库允许你发送文件。以下是一个简单的示例:
import requests
# 发送文件
response = requests.post("http://www.example.com/upload", files={"file": open("example.txt", "rb")})
# 打印响应体
print(response.text)
实例34:使用Python的urllib库发送文件
urllib库也允许你发送文件。以下是一个简单的示例:
import urllib.request
import urllib.parse
# 发送文件
files = {"file": open("example.txt", "rb")}
req = urllib.request.Request("http://www.example.com/upload", data=urllib.parse.urlencode(files).encode())
# 获取响应
response = urllib.request.urlopen(req)
# 打印响应体
print(response.read())
实例35:使用Python的http.client模块发送文件
http.client模块也允许你发送文件。以下是一个简单的示例:
import http.client
import urllib.parse
# 创建连接
conn = http.client.HTTPConnection("www.example.com")
# 发送文件
conn.request("POST", "/upload", body=urllib.parse.urlencode({"file": open("example.txt", "rb")}).encode())
# 获取响应
response = conn.getresponse()
# 打印响应体
print(response.read())
# 关闭连接
conn.close()
实例36:使用Python的aiohttp库发送异步文件
aiohttp库也允许你发送异步文件。以下是一个简单的示例:
”`python import aiohttp
async def fetch(session, url, file):
async with session.post(url, data={"file": file}) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as
