python中Requests发送json格式的post请求方法
一、post请求传body的参数有两种:data和json,那么我们来看一下python各种数据结构做为body传入的表现1.普通string类型
string2 = "2222222"
r = requests.post("http://httpbin.org/post", data=string2)
print(r.text)

二、string内是字典的
import requests
string = "{'key1': 'value1', 'key2': 'value2'}"
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)

三、元组(嵌套列表或者)
import requests
string = (['key1', 'value1'],)
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)

四、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)

五、传入非嵌套元组或列表
string = ['key1','value1']
r = requests.post("http://httpbin.org/post", data=string)
print(r.text)
六、以post(url,json=data)请求
dic = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", json=dic)
print(r.text)

七、文件
import requestsurl = "http://www.xxxx.net/login"#参数拼凑,附件上传格式如picurl参数,其他表单参数值拼成tuple格式:2-tuples (filename, fileobj),3-tuples (filename, fileobj, contentype),4-tuples (filename, fileobj, contentype, custom_headers)files = {"username": (None, "billy"), "password": (None, "abcd1234"), 'picUrl': ('pic.png', open('E:\\download\\pic.png', 'rb'), 'image/png')}#如需headers,不需要赋值Content-Type,不然可能会报错res = requests.post(url, files=files)print res.request.bodyprint res.request.headers

浙公网安备 33010602011771号