0
点赞
收藏
分享

微信扫一扫

Python实战:使用requests通过post方式提交json数据


目录

  • ​​方式一:提交dict​​
  • ​​方式二:提交string​​
  • ​​进一步优化​​

安装依赖

pip install requests

方式一:提交dict

该方式比较简单,可以直接提交​​json​​参数提交

# -*- coding: utf-8 -*-

import requests

url = 'http://httpbin.org/post'
data = {
'name': 'Tom',
'age': 20
}

res = requests.post(url, json=data)
print(res.text)

返回数据

{
"args": {},
"data": "{\"name\": \"Tom\", \"age\": 20}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "26",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.28.1",
"X-Amzn-Trace-Id": "Root=1-635f3812-432dff7a0625e9331bb8d78d"
},
"json": {
"age": 20,
"name": "Tom"
},
"origin": "1.202.253.34",
"url": "http://httpbin.org/post"
}

方式二:提交string

通过自定义请求体提交json数据

# -*- coding: utf-8 -*-

import json

import requests

url = 'http://httpbin.org/post'
data = {
'name': 'Tom',
'age': 20
}

# 先序列化成json数据
data_raw = json.dumps(data)
print(data_raw)
# {"name": "Tom", "age": 20}

res = requests.post(url, data=data_raw)
print(res.text)

返回数据

{
"args": {},
"data": "{\"name\": \"Tom\", \"age\": 20}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "26",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.28.1",
"X-Amzn-Trace-Id": "Root=1-635f38b0-37b9f6261c85922202d35ee8"
},
"json": {
"age": 20,
"name": "Tom"
},
"origin": "61.48.42.110",
"url": "http://httpbin.org/post"
}

进一步优化

我们可以发现,方式二提交的数据缺少了一个请求头

{
"Content-Type": "application/json"
}

虽然可以识别为json数据,不过有的后端框架有可能不能够正常识别json数据

完善代码

# -*- coding: utf-8 -*-

import json

import requests

url = 'http://httpbin.org/post'
data = {
'name': 'Tom',
'age': 20
}

# 先序列化成json数据
data_raw = json.dumps(data)
print(data_raw)
# {"name": "Tom", "age": 20}

# 增加请求头
headers = {
"Content-Type": "application/json; charset=UTF-8"
}

res = requests.post(url, data=data_raw, headers=headers)
print(res.text)

返回数据

{
"args": {},
"data": "{\"name\": \"Tom\", \"age\": 20}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "26",
"Content-Type": "application/json; charset=UTF-8",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.28.1",
"X-Amzn-Trace-Id": "Root=1-635f3956-7d2bf56b737dd06278d54b80"
},
"json": {
"age": 20,
"name": "Tom"
},
"origin": "61.48.42.110",
"url": "http://httpbin.org/post"
}


举报

相关推荐

0 条评论