python中Requests发送json格式的post请求方法

问题:做requests请求时遇到如下报错:

{“code”:“500”,“message”:"JSON parse error: Cannot construct instance of 
com.bang.erpapplication.domain.User (although at least one Creator exists): no String-argument
constructor/factory method to deserialize from String value

原因:
Requests.post源码如下:

def post(url, data=None, json=None, **kwargs):
    r"""Sends a POST request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary, list of tuples, bytes, or file-like
        object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request('post', url, data=data, json=json, **kwargs)

post请求传body的参数有两种:data和json,那么我们来看一下python各种数据结构做为body传入的表现1.普通string类型

string2 = "2222222"
r = requests.post("http://httpbin.org/post", data=string2)
print(r.text)

image2.string内是字典的

import requests
string = "{'key1': 'value1', 'key2': 'value2'}"
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)

image

3.元组(嵌套列表或者)

import requests
string = (['key1', 'value1'],)
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)

image

4.字典image5.json

import requests
import json

dic = {'key1': 'value1', 'key2': 'value2'}
string = json.dumps(dic)
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)

image

6.传入非嵌套元组或列表

string = ['key1','value1']
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)

image7.以post(url,json=data)请求

dic = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", json=dic)
print(r.text)

image

结论:

所以当你请求的data=dict时,未转为JSON的情况下,requests默认以表单形式key/value形式提交请求

setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");

以json=dict形式请求时,以application/json格式发出请求

setRequestHeader("Content-type","application/json; charset=utf-8");

以data=其它请求时,默认就按纯文本格式请求:

setRequestHeader("Content-type", "text/plain; charset=utf-8");

转载出处

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年8月16日
下一篇 2023年8月16日

相关推荐