Python: httplib error: cannot send 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()

An error occurs:

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

If I comment putheaderand endheaders, it works fine. But I need him to support life.

Does anyone know what I did wrong?

+3
source share
2 answers

Use putrequestinstead request. Since requestit can also send headers, it sends an empty string to the server to indicate the end of the headers, so subsequent headers will send an error.

Alternatively, you can do it the way it 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()
+7
source

headers = { "Content-Type": "application/x-www-form-urlencoded",           "": "Keep-Alive",           "Referer": " http://www.tu.sitio.cl/",           "User-Agent": "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)

-1

Source: https://habr.com/ru/post/1759458/


All Articles