python: httplib error: can not send headers

前提是你 提交于 2019-12-23 17:49:01

问题


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

It raises an error:

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

If I comment out putheader and endheaders, it runs fine. But I need it to be keep alive.

Does anyone know what I did wrong?


回答1:


Use putrequest instead of request. Since request also can send headers, it will send a blank line to the server to indicate end of headers, so sending headers afterward will create an error.

Alternatively, you could do as is done 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()



回答2:


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

code+

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



来源:https://stackoverflow.com/questions/3473583/python-httplib-error-can-not-send-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!