无法从urllib2获得预期的JSON

时间:2013-09-24 19:24:59

标签: python curl urllib2

我正在尝试与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()

1 个答案:

答案 0 :(得分:1)

没关系 - 显然答案是请求库远远优于urllib2。花了我大约十秒钟。