简体   繁体   中英

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?

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)
url="https://somedomain.com/someFile.php"
params = {"abc":"text without quote symbols", "someParam":.... }
res=requests.post(url, params=params)
print(res.text) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM