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

4 投票
2 回答
16314 浏览
提问于 2025-04-16 02:44
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 个回答

-1

这里有一段代码,主要是设置一些请求的头信息。头信息就像是你在网上发信息时附带的标签,告诉对方你是谁,想要做什么。

在这段代码中,

  • Content-Type:这表示你发送的数据类型是“表单数据”,就像填写表格一样。
  • Connection:这里的“Keep-Alive”意思是希望保持连接,不要每次都重新建立连接,这样可以提高效率。
  • Referer:这是你访问的来源网址,告诉服务器你是从哪个页面过来的。
  • User-Agent:这个信息是关于你使用的浏览器和操作系统的,帮助服务器了解你在用什么设备。

接下来是一个请求的代码:

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

这行代码的意思是:用“POST”方法向“/formulario/”这个地址发送数据,数据内容是“params”,并且使用刚才设置的头信息“headers”。

9

使用 putrequest 而不是 request。因为 request 也可以发送头信息,它会向服务器发送一个空行来表示头信息的结束,所以如果之后再发送头信息,就会出错。

另外,你也可以按照 这里 的做法来操作:

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

撰写回答