python - python请求数据中发送 "\r\n"符号

标签 python python-requests

curl 一切正常:

curl -v "http://user:password@localhost/_control.html" -d $'data1=1\r\n'

我在 python 中尝试过这种方式:

url = "http://localhost/_control.html"

payload = {'data1': '1\r\n'}

headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}

r = requests.post(url, data=payload, headers=headers, auth=('user', 'password'))

但它不起作用。在这种情况下,内容长度是 13 而不是 9(使用 curl 请求)

是否可以使用 python 请求发送相同的数据(以\r\n 结尾)?

最佳答案

\r\n 字符被 URL 编码,因为它们应该是,因为 application/x-www-form-urlencoded数据cannot contain those characters directly :

Non-alphanumeric characters are replaced by %HH, a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A).

使用 this technique 记录从 Python 发送的请求,我们可以看到它正确发送了这 13 个字节:

data1=1%0D%0A

curl 的例子中,它的手册页没有提到你传递给 -d/--data 的任何编码,所以大概您应该在将字符串传递给 curl 之前自己对字符串进行编码。我们可以用 --trace-ascii - 确认这一点:

=> Send data, 9 bytes (0x9)
0000: data1=1

\r\n 对在这里没有清楚地显示,但我们可以推断它没有编码,因为字节数。

简而言之,您使用 curl 命令发送的请求一开始是无效的。

关于python - python请求数据中发送 "\r\n"符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63829869/

相关文章:

python - 将行条目与列名称连接起来

android - Kivy SQLalchemy 和 Android,没有名为 MySQLdb 的模块

elasticsearch - 使用Python请求更新ElasticSearch文档

python-3.x - Python3请求模块PUT空文件

python - IPython 笔记本和 SQL : 'ImportError: No module named sql' when running '%load_ext sql'

python - 在 for 循环中不匹配时退出 python 脚本

python - 如何从 pandas 数据框中获取同一行(前一列)的前一个值?

python - 使用 Pushes Create Api with Python 将文件上传/推送到 Azure Devops Repo 时如何查找 oldobjectid

python - PyPy:导入错误:没有名为请求的模块

python - 如何让 Python 请求信任自签名 SSL 证书?