Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Requests: Invalid Header Name

I am trying to send a request with the header: ":hello". However, the leading colon causes the script to not function properly, and emit this traceback:

Traceback (most recent call last):

(first few lines removed for my privacy)

File "C:\Python27\lib\site-packages\requests\api.py", line 109, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python27\lib\site-packages\requests\adapters.py", line 370, in send
    timeout=timeout
  File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 559, in urlopen
    body=body, headers=headers)
  File "C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 353, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Python27\lib\httplib.py", line 1057, in request
    self._send_request(method, url, body, headers)
  File "C:\Python27\lib\httplib.py", line 1096, in _send_request
    self.putheader(hdr, value)
  File "C:\Python27\lib\httplib.py", line 1030, in putheader
    raise ValueError('Invalid header name %r' % (header,))
ValueError: Invalid header name ':hello'

Is there a workaround for this? My script is:

import requests
headers = {'user-agent': 'alsotesting', ':hello': 'test'}
requests.post("my server", headers=headers)
like image 263
Rob Avatar asked Dec 19 '15 14:12

Rob


1 Answers

As your error says, :header is not a valid HTTP header name (you cannot start headers with ":" - see documentation). You should change

headers = {'user-agent': 'alsotesting', ':hello': 'test'}

to

headers = {'user-agent': 'alsotesting', 'hello': 'test'}

Edit: HTTP/2 uses pseudo-headers fields, which start with a colon (see documentation). Also, as explained here, you may see some headers starting with a colon in Chrome's Developer Tools, which can happen when Chrome is talking to a web server using SPDY - and also HTTP/2 (which is based on SPDY/2), which correspond to pseudo-headers. As stated in documentation, pseudo-header fields are not HTTP header fields.

In conclusion, header fields starting with a colon are not allowed with standard HTTP protocol, so that is why you are getting the Invalid header name error

like image 160
Gabriel Ilharco Avatar answered Oct 17 '22 06:10

Gabriel Ilharco