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))
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐