我正在玩,尝试编写一些代码来使用tr.im API来缩短URL。在阅读http://docs.python.org/library/urllib2.html后,我尝试了: TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip()response.code是200(我认为它应该是202)。url有效,但基本的HTTP身份验证似乎没有用,因为缩短的URL不在我的URL列表中(在http://tr.im/?page=1)。如果我使用查询字符串参数而不是基本HTTP身份验证,如下所示: TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&username=%s&password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip()...然后不仅url有效,而且它记录在我的tr.im帐户中。(虽然response.code仍然是200.)虽然我的代码一定有问题(而不是tr.im的API),因为$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk如果我跑:$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk...再次,我得到:{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"}注意代码是201,消息是“tr.im URL已经创建[yacitus]”。我不能正确地进行基本的HTTP身份验证(在任一种尝试中)。你能发现我的问题吗?也许我应该看一下,通过电线发送什么?我以前从未这样做过。我可以使用Python API(可能在pdb中)吗?或者我可以使用另一种工具(最好是Mac OS X)吗?
3 回答

鸿蒙传说
TA贡献1865条经验 获得超7个赞
为了使urllib2基本身份验证起作用,http响应必须包含HTTP代码401 Unauthorized 和一个"WWW-Authenticate"带有值的密钥,"Basic"否则Python将不会发送您的登录信息,您将需要使用请求,或者urllib.urlopen(url)使用您的登录信息。 url,或添加@Flowpoke的 答案中的标题。
您可以通过以下方式查看错误urlopen:
try:
urllib2.urlopen(urllib2.Request(url))
except urllib2.HTTPError, e:
print e.headers
print e.headers.has_key('WWW-Authenticate')
添加回答
举报
0/150
提交
取消