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

输出结果如下:
python3 requests设置headers = {‘Content-Type‘: ‘application/json‘ }未生效,解决方案_第1张图片

解决方法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))

运行结果如下:
python3 requests设置headers = {‘Content-Type‘: ‘application/json‘ }未生效,解决方案_第2张图片

解决方法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))

你可能感兴趣的:(python,测试,python)