Python 请求模块发送 JSON 字符串而不是 x-www-form-urlencoded 参数字符串 [英] Python requests module sends JSON string instead of x-www-form-urlencoded param string
问题描述
我的印象是使用 x-www-form-urlencoded 规范的 POSTS 应该在帖子正文中发送一个 URL 编码的参数字符串.但是,当我这样做时
I was under the impression that POSTSs using x-www-form-urlencoded specifications should send a URL encoded param string in the body of the post. However, when I do this
data = json.dumps({'param1': 'value1', 'param2': 'value2'})
Requests.post(url, data=data)
接收端的请求正文如下所示:
The body of the request on the receiving end looks like this:
{"param1": "value1", "param2": "value2"}
但我期待得到这个
param1=value1¶m2=value2
如何获取以第二种形式发送数据的请求?
How I can get Requests to send the data in the second form?
推荐答案
你得到 JSON 的原因是你显式调用 json.dumps
来生成一个 JSON 字符串.只是不要那样做,你不会得到一个 JSON 字符串.换句话说,将您的第一行更改为:
The reason you're getting JSON is because you're explicitly calling json.dumps
to generate a JSON string. Just don't do that, and you won't get a JSON string. In other words, change your first line to this:
data = {'param1': 'value1', 'param2': 'value2'}
正如文档所解释的那样,如果您将 dict 作为 data
值传递,它将被表单编码,而如果您传递一个字符串,它将按原样发送.
As the docs explain, if you pass a dict as the data
value, it will be form-encoded, while if you pass a string, it will be sent as-is.
例如,在一个终端窗口中:
For example, in one terminal window:
$ nc -kl 8765
在另一个:
$ python3
>>> import requests
>>> d = {'spam': 20, 'eggs': 3}
>>> requests.post("http://localhost:8765", data=d)
^C
>>> import json
>>> j = json.dumps(d)
>>> requests.post("http://localhost:8765", data=j)
^C
在第一个终端中,您会看到第一个请求正文是这样的(和 Content-Type application/x-www-form-urlencoded
):
In the first terminal, you'll see that the first request body is this (and Content-Type application/x-www-form-urlencoded
):
spam=20&eggs=3
... 而第二个是这个(并且没有 Content-Type):
… while the second is this (and has no Content-Type):
{"spam": 20, "eggs": 3}
这篇关于Python 请求模块发送 JSON 字符串而不是 x-www-form-urlencoded 参数字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!