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

Gre*_*rey 3 python httprequest httplib http-headers

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()
Run Code Online (Sandbox Code Playgroud)

它引发了一个错误:

  conn.putheader('Connection','Keep-Alive')
  File "D:\Program Files\python\lib\httplib.py", line 891, in putheader
    raise CannotSendHeader()
Run Code Online (Sandbox Code Playgroud)

如果我注释掉putheaderendheaders,它运行良好.但我需要它保持活力.

有谁知道我做错了什么?

sje*_*397 8

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()
Run Code Online (Sandbox Code Playgroud)

  • 你使用`request`而不是`putrequest`来完成整个请求是错的.在让请求通过之前你需要添加一些标题,而`putrequest`就是这样做的. (2认同)