我们以访问百度主页为案例,使用socket发送http请求。

import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('www.baidu.com',80))
s.send('''GET https://www.baidu.com/ HTTP/1.1
Host: www.baidu.com
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Accept-Language: zh-CN,zh;q=0.8

''')

buf=s.recv(1024)
while len(buf):
    print buf
    buf = s.recv(1024)
 

基于socket进行http编程在于请求参数的可控性更好,但是难度相应就更大了。以上发送的数据是直接从fiddler抓包器里面复制的。


已注销
981 声望48 粉丝

Focus on programming efficiency