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/