Python Request | Construct Post Request Body
I am trying to construct below POST request using python requests. Request header Host: www.example.com User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:46.0) Gecko/20100101 Fi
Solution 1:
Your error is as per the comments to this answer from using an ancient version of requestes 1.1.0
from 2013, so pip install -U requests
will fix that.
To do the post you don't need to hardcode anything, you create a session and get whatever you need i.e the csrf token and requests will take care of the rest:
import requests
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:46.0) Gecko/20100101 Firefox/46.0',
'X-Requested-With': 'XMLHttpRequest', "referer": "https://www.hackerearth.com/challenges/"}
with requests.Session() as s:
s.get("https://www.hackerearth.com")
headers["X-CSRFToken"] = s.cookies["csrftoken"]
r = s.post("https://www.hackerearth.com/AJAX/filter-challenges/?modern=true", headers=headers,
files={'submit': (None, 'True')})
print(r.json())
The three necessary things were, X-Requested-With
as it has to be an ajax request, the referer
and the csrf
token.
To access the raw request data, you can access the attributes on r.request
:
print(r.request.body)
print(r.request.headers)
Post a Comment for "Python Request | Construct Post Request Body"