简体   繁体   English

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

[英]Setting Content-Type / application/json in header

I'm using urllib2 to create an HTTP request, I need to set Content-Type : application/json in the header, but it doesn't seem to be working 我正在使用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")

The results are: 结果是:

Data: "type":"chain","data":null 数据:“类型”:“链”,“数据”:空

Accept: application/json 接受:application / json

Content-Type: None 内容类型:无

Authorization: Basic U1lTQ1RMOmFiYzEyMw== 授权:基本U1lTQ1RMOmFiYzEyMw ==

As you can see, even though I'm setting "Content Type", its coming back "None". 如您所见,即使我设置了“内容类型”,它也会返回“无”。

Any help would be appreciated 任何帮助,将不胜感激

That's because of an inconsistency in the urllib2.Request header accessor methods - namely, add_header() auto-capitalizes your header when storing, but get_header() doesn't do the same when retrieving, so if you do: 这是因为在不一致的urllib2.Request头存取方法-即add_header()存储时,但自动大写你的头get_header()检索时并不尽相同,因此,如果你这样做:

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

or 要么

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

everything should show up fine. 一切应该都很好。 Headers, by all HTTP specifications, should be treated as case-insensitive anyway, sadly most HTTP libraries out there doesn't respect that fact. 按照所有HTTP规范,标头无论如何都不应区分大小写,可悲的是,大多数HTTP库都不尊重这一事实。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM