python3 http协议

网上下了个pdf,据说是python3的网络编程的,结果看了才知道,只针对python2系列,没办法,只好看python的官方文档,安装目录C:\Python34下有个Doc目录,打开其中的文件python340.chm,很轻易就能发现http的主题,以下内容为获取一个风页内容。

只有一点需要注意,read()获取的为byte字节流,打印时应进行编码,这里编码为utf-8格式。

以下为代码:

#!/usr/bin/env python3.4
import http.client
conn = http.client.HTTPConnection("www.xcplay.cn")
conn.request("GET", "/game_center.php")
r1 = conn.getresponse()
print(r1.status, r1.reason)

data1 = r1.read()  # This will return entire content.
print(data1.decode('utf-8'))
conn.close()


关于post的数据,这儿加了一些参数设置,以下代码为调试某虚拟机的指令

#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  

import http.client
import urllib
port=2861
HEADERS = {"Content-type": "application/x-www-form-urlencoded",
           "User-Agent":"BlueStacks/0.8.0.2997/39961f1d-f5fa-11e3-a683-00232447e41c gzip"}

headers = HEADERS
postdata = urllib.parse.urlencode({'package': 'com.tencent.pao', 'activity': 'com.tencent.pao.BreezeGame'})  
postdata = postdata.encode('utf-8') 
headers["Content-length"] = len(postdata)
conn = http.client.HTTPConnection("127.0.0.1", port)
conn.request("POST", "/runapp", postdata, headers)
r1 = conn.getresponse()
print(r1.status, r1.reason)

data1 = r1.read()  # This will return entire content.
print(data1.decode('utf-8'))
conn.close()


你可能感兴趣的:(python)