软件开发定制定制python中Requests发送json格式的post请求

问题:
软件开发定制定制做请求时遇到如下报错

{“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源码如下:

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

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

返回的结果

2.string内是字典的

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

返回结果

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

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

返回结果:

4.字典

5.json

import requestsimport jsondic = {'key1': 'value1', 'key2': 'value2'}string = json.dumps(dic)r = requests.post("http://httpbin.org/post", data=string)print(r.text)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

返回结果

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

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

返回报错

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

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

运行结果

由以上运行结果可以看出:

转入参数body数据类型headers(Content-type)
datastringtext/plain纯文本(默认)
data元组(嵌套)text/plain纯文本(默认)–转为dict
data元组(非嵌套)报错,不支持
data列表报错,不支持
data字典application/x-www-form-urlencoded(key/value表单)
datajson(字符串但!= python string)text/plain纯文本(默认)-要再做验证
json字典(源码内转成了json)application/json(json串)

现在让我们来看一下源码:
当转入json=data时:

当输入data=data时:

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

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

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

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

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

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

以上内容为原创内容,纯属个人理解,转载请注明出处。

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发