python:httplib错误:无法发送标头

时间:2010-08-13 02:58:39

标签: python http-headers httprequest 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()

如果我发表评论putheaderendheaders,它就可以正常运行了。但我需要它保持活力。

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:8)

使用putrequest代替request。由于request也可以发送标题,因此它会向服务器发送一个空行以指示标题的结尾,因此之后发送标题会产生错误。

或者,您可以按照here完成:

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("musi-cal.mojam.com:80")
conn.request("POST", "/cgi-bin/query", params, headers)
response = conn.getresponse()

答案 1 :(得分:-1)

headers = {" Content-Type":" application / x-www-form-urlencoded",            "连接":"保活&#34 ;,            " Referer的":" http://www.tu.sitio.cl/&#34 ;,            " 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)