python: httplib 错误:无法发送标头
conn = httplib.HTTPConnection('thesite')
conn.request("GET","myurl")
conn.putheader('Connection','Keep-Alive')
#conn.putheader('User-Agent','Mozilla/5.0(Windows; u; windows NT 6.1;en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome//5.0.375.126 Safari//5.33.4')
#conn.putheader('Accept-Encoding','gzip,deflate,sdch')
#conn.putheader('Accept-Language','en-US,en;q=0.8')
#conn.putheader('Accept-Charset','ISO-8859-1,utf-8;1=0.7,*;q=0.3')
conn.endheaders()
r1= conn.getresponse()
它会引发错误:
conn.putheader('Connection','Keep-Alive')
File "D:\Program Files\python\lib\httplib.py", line 891, in putheader
raise CannotSendHeader()
如果我注释掉 putheader
和 endheaders
,它运行正常。但我需要它保持活力。
有谁知道我做错了什么?
conn = httplib.HTTPConnection('thesite')
conn.request("GET","myurl")
conn.putheader('Connection','Keep-Alive')
#conn.putheader('User-Agent','Mozilla/5.0(Windows; u; windows NT 6.1;en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome//5.0.375.126 Safari//5.33.4')
#conn.putheader('Accept-Encoding','gzip,deflate,sdch')
#conn.putheader('Accept-Language','en-US,en;q=0.8')
#conn.putheader('Accept-Charset','ISO-8859-1,utf-8;1=0.7,*;q=0.3')
conn.endheaders()
r1= conn.getresponse()
It raises an error:
conn.putheader('Connection','Keep-Alive')
File "D:\Program Files\python\lib\httplib.py", line 891, in putheader
raise CannotSendHeader()
If I comment out putheader
and endheaders
, it runs fine. But I need it to be keep alive.
Does anyone know what I did wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
putrequest
而不是request
。由于request
也可以发送标头,因此它会向服务器发送一个空行以指示标头结束,因此稍后发送标头会产生错误。或者,您可以按照此处的方式进行操作:
Use
putrequest
instead ofrequest
. Sincerequest
also can send headers, it will send a blank line to the server to indicate end of headers, so sending headers afterward will create an error.Alternatively, you could do as is done here:
headers = {"Content-Type":"application/x-www-form-urlencoded",
"连接":"保持活动",
"推荐人":"http://www.tu.sitio.cl/",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36(KHTML,如 Gecko)Chrome/51.0.2704.103 Safari/537.36"};
代码+
conn.request(方法=“POST”,url=“/formulario/”,body=params,headers=headers)
headers = {"Content-Type":"application/x-www-form-urlencoded",
"Connection":"Keep-Alive",
"Referer":"http://www.tu.sitio.cl/",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"};
code+
conn.request(method="POST", url="/formulario/", body=params, headers=headers)