如何使用urllib2在Python中发送头

如何使用urllib2在Python中发送头,python,json,Python,Json,我正在尝试从网站请求API,如果我没有发送 接受:application/vnd.travis ci.2+json 对于标头,响应将以XML格式出现。我想要的是JSON格式。所以,我需要发送带有blow代码的标题 url = 'https://api.example.org/books/title' import json, urllib2 response = urllib2.urlopen(url) jsonString = response.read() repo = json.loads

我正在尝试从网站请求API,如果我没有发送

接受:application/vnd.travis ci.2+json

对于标头,响应将以XML格式出现。我想要的是JSON格式。所以,我需要发送带有blow代码的标题

url = 'https://api.example.org/books/title'
import json, urllib2
response = urllib2.urlopen(url)
jsonString = response.read()
repo = json.loads(jsonString)

上面没有做任何事情,因为url是以xml格式返回的,除非我将Accept:application/vnd.travis ci.2+json添加到请求中

request = urllib2.Request(url , headers={"Accept" : "application/json"})
更新


您不能直接使用urlopen来实现这一点,但可以使用Request


您可以使用请求传递自定义标头。还可以看到丹尼尔·罗斯曼的答案,他更快地给出了相同的答案

 import urllib2
 request = urllib2.Request("https://api.example.org/books/title", headers={"Accept" : "application/vnd.travis-ci.2+json"})
 contents = urllib2.urlopen(request).read()

那么,我应该用我的代码替换那一行吗?我该如何处理请求变量?将请求传递给urlopen response=urllib2.urlopenrequest对不起,至少您的第一个请求起作用了。但是第二个什么也没有给我,第一个显示的是序列化数据,而不是json响应。
request = urllib2.Request(url, headers={'Accept': 'application/vnd.travis-ci.2+json'})
response = urllib2.urlopen(request)
 import urllib2
 request = urllib2.Request("https://api.example.org/books/title", headers={"Accept" : "application/vnd.travis-ci.2+json"})
 contents = urllib2.urlopen(request).read()