Skip to content

Commit 890a76e

Browse files
committed
Create http_client.py
1 parent 4e642ad commit 890a76e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

socket/http_client.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
'a socket example which get html data from www.sina.com.cn'
5+
6+
import socket
7+
8+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
9+
# 建立连接:
10+
s.connect(('www.sina.com.cn', 80))
11+
# 发送数据:
12+
s.send('GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
13+
# 接收数据:
14+
buffer = []
15+
while True:
16+
# 每次最多接收1k字节:
17+
d = s.recv(1024)
18+
if d:
19+
buffer.append(d)
20+
else:
21+
break
22+
data = ''.join(buffer)
23+
# 关闭连接:
24+
s.close()
25+
26+
header, html = data.split('\r\n\r\n', 1)
27+
print header
28+
# 把接收的数据写入文件:
29+
with open('sina.html', 'wb') as f:
30+
f.write(html)

0 commit comments

Comments
 (0)