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

编程知识 更新时间:2023-04-05 05:39:59

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

更多推荐

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

本文发布于:2023-04-05 05:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/868c35ef470eda0e3b9e1ec3c6a46e9e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:解决方案   headers   requests   Content   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 45059文章数
  • 14阅读数
  • 0评论数