4
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()

如果我注释掉putheaderand endheaders,它运行良好。但我需要它来保持活力。

有谁知道我做错了什么?

4

2 回答 2

9

使用putrequest而不是request. 由于request也可以发送 headers,它会向服务器发送一个空行来指示 headers 的结束,因此之后发送 headers 会产生错误。

或者,您可以按照此处的方式进行操作:

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()
于 2010-08-13T03:11:02.547 回答
-1

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"};

代码+

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

于 2016-07-19T16:39:12.397 回答