Omit headers in requests POST request
Question: I am making a POST request using the `import requests` library. It's adding
some headers to the request that I suspect is making it fail...

    
    
    r = requests.post(url, headers = {"Content-Type" : "text/zinc; charset=utf-8"}, \
                      cookies = {"cookie":cookie}, \
                      data = data)
    

Here's the results of `r.request.headers`...

    
    
    CaseInsensitiveDict({
        'Accept': '*/*',
        'Content-Type': 'text/zinc; charset=utf-8',
        'Accept-Encoding': 'gzip, deflate, compress',
        'User-Agent': 'python-requests/2.2.1 CPython/3.4.0 Linux/3.13.0-52-generic',
        'Cookie': 'cookie=mycookie; fanws="mycookie"'
    })
    

So the question is, how do I only include the headers that I specified?


Answer: If you really want to do this, you can create a
[`PreparedRequest`](http://docs.python-
requests.org/en/latest/user/advanced/#prepared-requests) and then edit its
headers before sending it. This is unlikely to help you here—but it may be
worth doing just to convince yourself that it's not going to help, so…

Instead of this:

    
    
    r = requests.post(url, headers = {"Content-Type" : "text/zinc; charset=utf-8"}, \
                      cookies = {"cookie":cookie}, \
                      data = data)
    

Do this:

    
    
    sess = requests.Session()
    req = requests.Request('GET', url, 
                           headers={"Content-Type": "text/zinc; charset=utf-8"},
                           cookies={"cookie": cookie},
                           data=data)
    preq = req.prepare()
    preq.headers = {key: value for key, value in preq.headers.items()
                    if key in {'Content-Type', 'Cookie'}}
    r = sess.send(preq)
    

It's in `prepare` that all the changes get done. You obviously want to keep
the `cookies` being turned into a `Cookie` header, but you don't want to keep
any of the other changes, so I just removed any header besides the one you
explicitly passed and `Cookie`. You can, of course, do anything else you want
there.

