[英]JsonResponse not setting content-type to application/json using django
[英]Setting Content-Type / application/json in header
我正在使用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")
结果是:
数据:“类型”:“链”,“数据”:空
接受:application / json
内容类型:无
授权:基本U1lTQ1RMOmFiYzEyMw ==
如您所见,即使我设置了“内容类型”,它也会返回“无”。
任何帮助,将不胜感激
这是因为在不一致的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库都不尊重这一事实。
我能够确定add_header()方法不喜欢大写的“ Type”,将其更改为request.add_header(“ Content-type”,“ application / json”)解决了该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.