我正在尝试与 Jira API 交互。我可以使用下面的 cURL 命令让它工作,并且我得到了我期望的 JSON,但是我需要编写一个 Python 脚本,所以我认为我应该使用 urllib2(所有这些东西对我来说都是新的)。这是我所能得到的:我收到 HTTP 错误 415:不支持的媒体类型。我尝试将其包含Content-Type: application/json
在标头中,但随后出现 HTTP 错误 400:错误请求。有什么想法吗?
import urllib2, urllib
import os.path
import cookielib
# curl -c cookie_jar -H "Content-Type: application/json" -d '{"username" : "XXXX", "password" : "XXXXXX"}' http://www.host.net/rest/auth/latest/session
COOKIEFILE = 'cookies.lwp'
urlopen=urllib2.urlopen
Request=urllib2.Request
cj = cookielib.LWPCookieJar()
if os.path.isfile(COOKIEFILE):
cj.load(COOKIEFILE)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
password_mgr = urllib2.HTTPPasswordMgr()
url = 'http://www.host.net/rest/auth/latest/session'
user = 'XXXX'
password = 'XXXXX'
realm = "http://www.host.net"
password_mgr.add_password(realm, url, user, password)
txheaders = {
'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',}
# "Content-Type" : "application/json"}
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
txdata = urllib.urlencode({"username" : "XXXX", "password" : "XXXXX"})
opener = urllib2.build_opener(handler)
req = Request(url, txdata, txheaders)
try:
handle = urlopen(req)
except urllib2.HTTPError, e:
print e.code
print e.read()