免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6917 | 回复: 5
打印 上一主题 下一主题

请问一下putrequest和request的区别 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-08-29 12:02 |只看该作者 |倒序浏览
最近学习http连接,碰到一个问题,如下代码
# -*- coding:utf-8 -*-

import httplib

conn = httplib.HTTPConnection("www.python.org")
conn.putrequest("GET","/index.html")
ret = conn.getresponse()
print ret.status,ret.reason
filetmp = file("test.html","wb+")
while True:
    f = ret.read()
    filetmp.write(f)
    if len(f) == 0:
        break
会raise一个异常
raise ResponseNotReady()
ResponseNotReady    如果用request 就不会,为什么啊,难道要加那个putheader?  request和putrequest到底有什么区别呢,新人学习,谢谢高手解答。

论坛徽章:
0
2 [报告]
发表于 2008-08-29 12:19 |只看该作者
request( method, url[, body[, headers]])

This will send a request to the server using the HTTP request method method and the selector url. If the body argument is present, it should be a string of data to send after the headers are finished. The header Content-Length is automatically set to the correct value. The headers argument should be a mapping of extra HTTP headers to send with the request.

putrequest( request, selector[, skip_host[, skip_accept_encoding]])

This should be the first call after the connection to the server has been made. It sends a line to the server consisting of the request string, the selector string, and the HTTP version (HTTP/1.1). To disable automatic sending of Host: or Accept-Encoding: headers (for example to accept additional content encodings), specify skip_host or skip_accept_encoding with non-False values. Changed in version 2.4: skip_accept_encoding argument added.

貌似应该是putrequest不会自动发送header部分,request是自动的,你可以看下官方docs

论坛徽章:
0
3 [报告]
发表于 2008-08-29 12:41 |只看该作者

回复 #2 xiaoyu9805119 的帖子

谢谢。doc和help我都看过了,写得很笼统。如果真是“貌似应该是putrequest不会自动发送header部分,request是自动的”的话大致明白了。不过我更想知道的是为什么要加header,那个header有啥用呢

论坛徽章:
0
4 [报告]
发表于 2008-08-29 13:00 |只看该作者
>>> import httplib
>>> con = httplib.HTTPConnection('www.163.com')
>>> con.putrequest('GET','/index.html')
>>> con.putheader('Accept','text/html')
>>> con.endheaders()
>>> ret=con.getresponse()
>>> ret.status
200
>>> aa=ret.read()
>>> aa[:10]
'<!DOCTYPE '

我试了下,如果不发送header过去的话就会有异常。con.putheader('Accept','text/html')这个可以没有,但是要调用endheaders这个。就OK了

论坛徽章:
0
5 [报告]
发表于 2008-08-29 13:23 |只看该作者

回复 #4 xiaoyu9805119 的帖子

嗯,谢谢了。我还以为putheader和endheader都必须要.
刚看了下putrequest和requeset这两个函数的源代码,大致明白了,确实request的header是默认发送的,发送了一个空的header: def request(self, method, url, body=None, headers={}):

论坛徽章:
0
6 [报告]
发表于 2008-08-29 13:27 |只看该作者
request是自动发送了,putrequest要手动下。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP