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

前端 未结 2 1168
时光取名叫无心
时光取名叫无心 2020-12-24 02:28

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

相关标签:
2条回答
  • 2020-12-24 03:06

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

    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
    

    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):

    spam=20&eggs=3
    

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

    {"spam": 20, "eggs": 3}
    
    0 讨论(0)
  • 2020-12-24 03:12

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

    # 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)}
    
    0 讨论(0)
提交回复
热议问题