python httpConnection详解

模块urllib,urllib2,httplib的区别

httplib实现了http和https的客户端协议,但是在python中,模块urllib和urllib2对httplib进行了更上层的封装。

介绍下例子中用到的函数:
1、HTTPConnection函数
httplib.HTTPConnection(host[,port[,stict[,timeout]]])

这个是构造函数,表示一次与服务器之间的交互,即请求/响应
host 标识服务器主机(服务器IP或域名)
port 默认值是80
strict 模式是False,表示无法解析服务器返回的状态行时,是否抛出BadStatusLine异常
例如:
conn = httplib.HTTPConnection(“192.168.81.16”,80) 与服务器建立链接。

2、HTTPConnection.request(method,url[,body[,header]])函数
这个是向服务器发送请求

method 请求的方式,一般是post或者get,
例如:
method=”POST”或method=”Get”

url 请求的资源,请求的资源(页面或者CGI,我们这里是CGI)
例如:
url=”http://192.168.81.16/cgi-bin/python_test/test.py” 请求CGI

或者:
url=”http://192.168.81.16/python_test/test.html” 请求页面

body 需要提交到服务器的数据,可以用json,也可以用上面的格式,json需要调用json模块
headers 请求的http头headerdata = {“Host”:”192.168.81.16”}
例如:
test_data = {‘ServiceCode’:’aaaa’,’b’:’bbbbb’}
test_data_urlencode = urllib.urlencode(test_data)
requrl = “http://192.168.81.16/cgi-bin/python_test/test.py
headerdata = {“Host”:”192.168.81.16”}
conn = httplib.HTTPConnection(“192.168.81.16”,80)
conn.request(method=”POST”,url=requrl,body=test_data_urlencode,headers = headerdata)
conn在使用完毕后,应该关闭,conn.close()

3、HTTPConnection.getresponse()函数
这个是获取http响应,返回的对象是HTTPResponse的实例。

4、HTTPResponse介绍:
HTTPResponse的属性如下:
read([amt]) 获取响应消息体,amt表示从响应流中读取指定字节的数据,没有指定时,将全部数据读出;
getheader(name[,default]) 获得响应的header,name是表示头域名,在没有头域名的时候,default用来指定返回值
getheaders() 以列表的形式获得header
例如:

date=response.getheader(‘date’);
print date
resheader=”
resheader=response.getheaders();
print resheader

列形式的响应头部信息:

[(‘content-length’, ‘295’), (‘accept-ranges’, ‘bytes’), (‘server’, ‘Apache’), (‘last-modified’, ‘Sat, 31 Mar 2012 10:07:02 GMT’), (‘connection’, ‘close’), (‘etag’, ‘“e8744-127-4bc871e4fdd80”’), (‘date’, ‘Mon, 03 Sep 2012 10:01:47 GMT’), (‘content-type’, ‘text/html’)]

date=response.getheader(‘date’);
print date

取出响应头部的date的值。

转载于:https://www.cnblogs.com/xinleishare/p/4381653.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值