首先,我了解还有其他模块,例如“请求”将更适合且更易于使用,但是我想使用套接字模块更好地理解HTTP。
我有一个执行以下操作的简单脚本:
客户端---> HTTP代理--->外部资源(GET Google.com)
我可以连接到HTTP代理,但是当我将google.com的GET请求标头发送到代理时,它根本无法为我提供任何响应。
#!/usr/bin/python
import socket
import sys
headers = """GET / HTTP/1.1\r\n
Host: google.com\r\n\r\n"""
socket = socket
host = "165.139.179.225" #proxy server IP
port = 8080 #proxy server port
try:
s = socket.socket()
s.connect((host,port))
s.send(("CONNECT {0}:{1} HTTP/1.1\r\n" + "Host: {2}: {3}\r\n\r\n").format(socket.gethostbyname(socket.gethostname()),1000,port,host))
print s.recv(1096)
s.send(headers)
response = s.recv(1096)
print response
s.close()
except socket.error,m:
print str(m)
s.close()
sys.exit(1)
要向代理发出HTTP请求,请打开与代理服务器的连接,然后发送HTTP代理请求。该请求与普通的HTTP请求基本相同,但是包含绝对URL而不是相对URL,例如
> GET http://www.google.com HTTP/1.1
> Host: www.google.com
> ...
< HTTP response
要发出HTTPS请求,请使用CONNECT方法打开一个隧道,然后在该隧道内正常进行,即进行SSL握手,然后在隧道内进行正常的非代理请求,例如
> CONNECT www.google.com:443 HTTP/1.1
>
< .. read response to CONNECT request, must be 200 ...
.. establish the TLS connection inside the tunnel
> GET / HTTP/1.1
> Host: www.google.com
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句