我在玩耍,尝试编写一些代码以使用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://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly之后, 我也尝试过:
TRIM_API_URL = 'api.tr.im/api'
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD)
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
response = urllib2.urlopen('http://%s/trim_simple?url=%s'
% (TRIM_API_URL, url_to_trim))
url = response.read().strip()
但我得到相同的结果。(response.code为200,URL有效,但未记录在我的帐户http://tr.im/上。)
如果我使用查询字符串参数代替基本的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()
...那么网址不仅有效,而且记录在我的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
...返回:
{"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":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"}
...并且该URL确实出现在http://tr.im/?page=1上的URL列表中。
如果我运行:
$ 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)?
"WWW-Authenticate"
并且在urllib2(或httplib2)发送您的凭据之前,代码为401。请参阅下面的答案。