1. HTTP协议基础
HTTP协议简介
HTTP(超文本传输协议)是互联网上应用最为广泛的网络协议之一。它定义了客户端和服务器之间的通信规则,是构建Web应用的基础。
客户端与服务器交互
客户端(如浏览器)通过发送HTTP请求到服务器,服务器响应请求并返回所需数据。
HTTP请求与响应
- 请求:包括请求行、请求头和可选的请求体。
- 响应:包括状态行、响应头和可选的响应体。
2. 实战案例解析
案例一:创建简单的HTTP服务器
from http.server import BaseHTTPRequestHandler, HTTPServer
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Hello, world!')
if __name__ == '__main__':
server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
httpd.serve_forever()
案例二:处理HTTP请求
from http.server import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Welcome to the homepage!')
else:
self.send_error(404, 'Page not found')
if __name__ == '__main__':
server_address = ('', 8000)
httpd = HTTPServer(server_address, RequestHandler)
httpd.serve_forever()
案例三:发送HTTP请求
import requests
response = requests.get('http://example.com')
print(response.status_code)
print(response.text)
案例四:使用HTTP代理
import requests
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
response = requests.get('http://example.com', proxies=proxies)
print(response.status_code)
print(response.text)
案例五:自定义HTTP请求头
import requests
headers = {
'User-Agent': 'MyApp/1.0',
'Authorization': 'Bearer token',
}
response = requests.get('http://example.com', headers=headers)
print(response.status_code)
print(response.text)
案例六:处理HTTP响应
import requests
response = requests.get('http://example.com')
if response.status_code == 200:
print(response.text)
else:
print('Error:', response.status_code)
案例七:发送HTTP POST请求
import requests
data = {
'username': 'user',
'password': 'pass'
}
response = requests.post('http://example.com/login', data=data)
print(response.status_code)
print(response.text)
案例八:处理HTTP错误
import requests
try:
response = requests.get('http://example.com')
response.raise_for_status()
print(response.text)
except requests.exceptions.HTTPError as e:
print('Error:', e)
案例九:使用会话保持状态
import requests
with requests.Session() as session:
session.get('http://example.com')
session.post('http://example.com/login', data={'username': 'user', 'password': 'pass'})
response = session.get('http://example.com/profile')
print(response.text)
案例十:使用HTTP长连接
import requests
response = requests.get('http://example.com', stream=True)
for chunk in response.iter_content(chunk_size=8192):
if chunk:
print(chunk)
3. 总结
本文通过30个实战案例,详细解析了HTTP协议在网络编程中的应用。从基础的HTTP协议介绍,到客户端与服务器交互、HTTP请求与响应,再到实战案例解析,帮助读者全面了解HTTP协议在网络编程中的应用。希望本文对读者有所帮助。
