http客户端
评论(0) 浏览量(3661)

http客户端

# -*- coding: cp936 -*-
'''
Created on 2011-8-4

@author: Administrator
'''
import httplib
url = "www.baidu.com"
port = httplib.HTTP_PORT
conn = httplib.HTTPConnection(url,port,timeout=10)
#conn.connect() 建立链接,可以不写

#conn.endheaders()
#data=conn.send("Hello")
#print data

#获取存在的网页
conn.request("GET", "/index.html")
r1 = conn.getresponse()
#读取源文件
data1 = r1.read()
#print("data1==========="+data1)
#打印状态码和 原因
print "=============",r1.status, r1.reason
#获取Http头信息
print "header1=================",r1.getheader("Server"),r1.getheader("Date")
header = r1.getheaders()
print "header2========",header

print "message=========",r1.msg
#获取http版本,如11=1.1
print "version=========",r1.version


#获取不存在的网页
conn.request("GET", "/parrot.spam")
r2 = conn.getresponse()
data2 = r2.read()
#print("data2==========="+data2)
print "=============",r2.status, r2.reason

#关闭连接
conn.close()


#例2
import httplib, urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
headers = {"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"}
conn = httplib.HTTPConnection("v.youku.com")
#可以带上HTTP头信息和参数~~这里的参数没作用
conn.request("POST", "/v_show/id_XMjkxMTc2MDEy.html", params, headers)
response = conn.getresponse()
print response.status, response.reason


 

没有登录不能评论