python:httplib错误:无法发送头

python:httplib错误:无法发送头,python,http-headers,httprequest,httplib,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

它引发了一个错误:

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()
如果我注释掉
putheader
endheaders
,它运行正常。但我需要它来维持生命


有人知道我做错了什么吗?

使用
putrequest
而不是
request
。由于
request
也可以发送头,它将向服务器发送一个空行,以指示头的结尾,因此随后发送头将产生错误

或者,您可以按原样操作:

headers={“内容类型”:“application/x-www-form-urlencoded”, “连接”:“保持活动状态”, “Referer”:“, “用户代理”:“Mozilla/5.0(Windows NT 6.1)AppleWebKit/537.36(KHTML,如Gecko)Chrome/51.0.2704.103 Safari/537.36”}

代码+


conn.request(method=“POST”,url=“/formulario/”,body=params,headers=headers)

错误在于您使用了
request
,而不是
putrequest
,从而完成了整个请求。在让请求通过之前,您需要添加一些头,而
putrequest
正是这样做的。您好,欢迎使用Stack Overflow!你能把你的答案注释得更清楚些吗?
  conn.putheader('Connection','Keep-Alive')
  File "D:\Program Files\python\lib\httplib.py", line 891, in putheader
    raise CannotSendHeader()
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()