Search code examples
pythonhttppython-requestsrequesthttp-post

How to handle special characters in python requests post request


I'm trying to send an HTTP POST request using the python requests package.

The working curl command looks like the following (captured from chrome dev tools network tab, right clicked on someFile.php, and chose "copy as cURL"). When run in a terminal, it outputs a valid, nonempty, response.

curl 'https://somedomain.com/someFile.php' \
  --data-raw $'abc=ZXC%20*%20QWE%20***%20BNM%20((someThing%20%3D%200))%20AND%20anotherThing%20%3E%3D%20\'2020-5-9\'%20IOP%20&someparam=1&myhash=a5d96895cab824fbd9bb85627a8f909d'

I attempted to replicate the POST request in python with:

import requests
url = 'https://somedomain.com/someFile.php'
out = requests.post(url,data=r'abc=ZXC%20*%20QWE%20***%20BNM%20((someThing%20%3D%200))%20AND%20anotherThing%20%3E%3D%20\'2020-5-9\'%20IOP%20&someparam=1&myhash=a5d96895cab824fbd9bb85627a8f909d')
print(out.text)

... but this just prints an empty string.

How do I handle this curl command in python?


Solution

  • Simply setting Content-Type header to application/x-www-form-urlencoded should solve your problem.

    headers={}
    headers["Content-Type"]="application/x-www-form-urlencoded"
    data="....."
    output=requests.post(url,headers=headers,data=data)