by
8,516 31
3
6
11k
82
Top 1% !
Popular
Famous
Pearl of Wisdom
Specified
MultiPlatform
Popularity: 414th place
No tags for this snippet yet.
LanguagePython
Languagetext
LicenseMIT_X11

How to add Cookies and Headers in HTTP requests in Python

Let's say I have an HTTP GET request and I want to decorate it with some Headers (e.g. "Accept" or "Authorization") and with some Cookies.
What's the best way to do this in Python?
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/117812/How-to-add-Cookies-and-Headers-in-HTTP-r?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
=> According to the api - http://docs.python-requests.org/en/latest/api/, the headers can all be passed in using requests.get: r=requests.get("http://www.example.com/", headers={"content-type":"text"}); => Response Headers: We can view the server’s response headers using a Python dictionary: >>> r.headers { 'status': '200 OK', 'content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'connection': 'close', 'server': 'nginx/1.0.4', 'x-runtime': '148ms', 'etag': '"e1ca502697e5c9317743dc078f67693f"', 'content-type': 'application/json; charset=utf-8' } => HTTP Headers are case-insensitive, so we can access the headers using any capitalization we want. >>> r.headers['Content-Type'] 'application/json; charset=utf-8' >>> r.headers.get('content-type') 'application/json; charset=utf-8' # If a header doesn’t exist in the Response, its value defaults to None: >>> r.headers['X-Random'] None => Cookies If a response contains some Cookies, you can get quick access to them: >>> url = 'http://http.org/cookies/set/requests-is/awesome' >>> r = requests.get(url) >>> r.cookies['requests-is'] 'awesome' # To send your own cookies to the server, you can use the cookies parameter: >>> url = 'http://http.org/cookies' >>> cookies = dict(cookies_are='working') >>> r = requests.get(url, cookies=cookies) >>> r.text '{"cookies": {"cookies_are": "working"}}'

Question

If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus