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

安装依赖

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"
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值