在标题中设置Content-Type / application / json

时间:2017-07-13 20:10:36

标签: python json content-type

我使用urllib2创建HTTP请求,我需要在标题中设置Content-Type:application / json,但它似乎没有工作

request = urllib2.Request(url, data='\"type\":\"chain\",\"data\":null')
request.add_header("Authorization", "Basic %s" % creds)
request.add_header("Content-Type", "application/json")
request.add_header("Accept", "application/json")
print "Data: %s" % request.get_data()
print "Accept: %s" % request.get_header("Accept")
print "Content-Type: %s" % request.get_header("Content-Type")
print "Authorization: %s" % request.get_header("Authorization")

结果是:

数据:"输入":"链","数据":null

接受:application / json

内容类型:无

授权:基本U1lTQ1RMOmFiYzEyMw ==

正如您所看到的,即使我正在设置"内容类型",它的回归"无"。

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

这是因为urllib2.Request标头访问器方法不一致 - 即,add_header()在存储时自动将标头大写,但get_header()在检索时不会执行相同操作,因此如果你这样做:

print "Content-Type: %s" % request.get_header("Content-type")

print "Content-Type: %s" % request.get_header("Content-Type".capitalize())
一切都应该显得很好。根据所有HTTP规范,标题应该被视为不区分大小写,遗憾的是大多数HTTP库都不尊重这一事实。

答案 1 :(得分:0)

我能够确定add_header()方法不喜欢大写“Type”,将其更改为request.add_header(“Content-type”,“application / json”)解决了问题。

相关问题