-2

For the simple request like following with python requests

r = requests.get("http://google.com", headers={'Connection': 'close'})

There are additional request headers sent with request like following

>>> r.request.headers
{'Connection': 'close', 'User-Agent': 'python-requests/2.9.1', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate'}

Is there any way to force python requests to just send the supplied headers and nothing more?

Thank you, Sudu

Sudu
  • 1
  • 2

3 Answers3

0

You need to send all other headers as None. For example:-

headers = {'Connection': 'close', 'Accept-Encoding': None, 'User-Agent': None}
r = requests.get("http://google.com", headers=headers)

P.S - But some websites may fail to respond if you send them as None

  • Thank you! :) setting `None` value to default headers ['Connection','User-Agent','Accept','Accept-Encoding'] sent by requests worked for my application. :) – Sudu Jun 18 '19 at 19:56
0

Please try 'head':

>>> r = requests.head('http://google.com',headers={'Connection':'close'})                                                               
>>> r.request.headers
{'Connection': 'close', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.19.1'}                    
>>> r.text                                                                                                                              
u'' 
v.coder
  • 1,822
  • 2
  • 15
  • 24
0

There are additional request headers sent with request like following

headers = {'Connection': 'close',  'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.19.1'}
r = requests.get("http://google.com", headers=headers)
  • 2
    OP already knows this. The question is not _whether_ they are sent, but rather how to _prevent_ those additional headers. – Nelewout Jun 06 '21 at 09:40