Python 请求模块发送 JSON 字符串而不是 x-www-form-urlencoded 参数字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26615756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:46:00  来源:igfitidea点击:

Python requests module sends JSON string instead of x-www-form-urlencoded param string

pythonpython-requests

提问by asolberg

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

我的印象是使用 x-www-form-urlencoded 规范的 POSTS 应该在帖子正文中发送一个 URL 编码的参数字符串。但是,当我这样做时

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"}

But I was expecting to get this

但我期待得到这个

param1=value1&param2=value2

How I can get Requests to send the data in the second form?

如何获得以第二种形式发送数据的请求?

采纳答案by abarnert

The reason you're getting JSON is because you're explicitly calling json.dumpsto 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:

您获得 JSON 的原因是因为您显式调用json.dumps以生成 JSON 字符串。只是不要这样做,您将不会得到 JSON 字符串。换句话说,将您的第一行更改为:

data = {'param1': 'value1', 'param2': 'value2'}

As the docsexplain, if you pass a dict as the datavalue, it will be form-encoded, while if you pass a string, it will be sent as-is.

正如文档所解释的,如果您传递一个 dict 作为data值,它将被表单编码,而如果您传递一个字符串,它将按原样发送。



For example, in one terminal window:

例如,在一个终端窗口中:

$ nc -kl 8765

In another:

在另一个:

$ 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

In the first terminal, you'll see that the first request body is this (and Content-Type application/x-www-form-urlencoded):

在第一个终端中,您将看到第一个请求正文是这个(和 Content-Type application/x-www-form-urlencoded):

spam=20&eggs=3

… while the second is this (and has no Content-Type):

...而第二个是这个(并且没有内容类型):

{"spam": 20, "eggs": 3}

回答by NotTooTechy

Important to add it does not work for nested json So, if you have

重要的是添加它不适用于嵌套的 json 所以,如果你有

# Wrong
data = {'param1': {'a':[100, 200]},
        'param2': 'value2',
        'param3': False}

# You have to convert values into string:
data = {'param1': json.dumps({'a':[100, 200]}),
        'param2': 'value2',
        'param3': json.dumps(False)}