![](/img/trans.png)
[英]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.