python3 http协议

来源:互联网 发布:岩土工程就业前景知乎 编辑:程序博客网 时间:2024/05/22 13:32

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

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

以下为代码:

#!/usr/bin/env python3.4import http.clientconn = 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.clientimport urllibport=2861HEADERS = {"Content-type": "application/x-www-form-urlencoded",           "User-Agent":"BlueStacks/0.8.0.2997/39961f1d-f5fa-11e3-a683-00232447e41c gzip"}headers = HEADERSpostdata = 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()


0 0