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)
2.string内是字典的
import requests
string = "{'key1': 'value1', 'key2': 'value2'}"
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)
3.元组(嵌套列表或者)
import requests
string = (['key1', 'value1'],)
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)
4.字典
5.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)
6.传入非嵌套元组或列表
string = ['key1','value1']
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)
7.以post(url,json=data)请求
dic = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", json=dic)
print(r.text)
结论:
所以当你请求的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");
json.loads --> 转字典
json.dumps --> 转json串
惜秦皇汉武,略输文采;唐宗宋祖,稍逊风骚。
一代天骄,成吉思汗,只识弯弓射大雕。
俱往矣,数风流人物,还看今朝