python3 requests设置headers = {‘Content-Type‘: ‘application/json‘ }未生效,解决方案

requests通过post请求,设置headers = {‘Content-Type’: ‘application/json’ }未生效问题

1、requests中,设置headers参数{‘Content-Type’: ‘application/json’ },是将请求数据以json的格式发送,而headers中默认请求方式是表单提交:{‘Content-Type’: ‘application/x-www-form-urlencoded’ };

问题:

设置了headers = {‘Content-Type’: ‘application/json’ },但未跑通接口,未返回正确数据,问题代码如下:

#coding = utf-8
import requests,json
url = 'http://xxxx'
data_login = {
    "mobile": "xxxx",
    "password": "123456"
}
headers = {
    'Content-Type': 'application/json'
}
res_login_status = requests.post(url=url+"/api/sys/login",data=data_login,headers=headers).json()
print(json.dumps(res_login_status,indent=4,ensure_ascii=False))

输出结果如下:
在这里插入图片描述

解决方法1:

headers = {‘Content-Type’: ‘application/json’ }的作用是将请求的数据转换为json格式上传,可以将上传的数据直接以json格式上传,可以请求成功;
代码如下:

#coding = utf-8
import pytest,requests,json
url = 'http://xxxx'
data_login = {
    "mobile": "1xxxx",
    "password": "123456"
}
headers = {
    'Content-Type': 'application/json'
}
res_login_status = requests.post(url=url+"/api/sys/login",data=json.dumps(data_login),headers=headers).json()
print(json.dumps(res_login_status,indent=4,ensure_ascii=False))

运行结果如下:
在这里插入图片描述

解决方法2

post请求时,传入json参数的数据,代码如下:

#coding = utf-8
import pytest,requests,json
url = 'http://xxxx'
data_login = {
    "mobile": "1xxxx",
    "password": "123456"
}
headers = {
    'Content-Type': 'application/json'
}
res_login_status = requests.post(url=url+"/api/sys/login",json=data_login,headers=headers).json()
print(json.dumps(res_login_status,indent=4,ensure_ascii=False))
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值