我正在尝试编写一些代码来使用 < a href = “ http://www.Programableweb.com/api/tr.im”rel = “ norefrer”> tr.im 缩短 URL 的 API。
在阅读了 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()
Code 是200(我认为应该是202) . url 是有效的,但是 基本的 HTTP 身份验证似乎不起作用,因为 缩短的 URL 不在我的 URL 列表中(在 http://tr.im/?page=1)。
在阅读了 < a href = “ http://www.voidspace.org.uk/python/article/entication.shtml # doing-it-”rel = “ norefrer”> 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()
... 那么不仅是网址有效,而且它记录在我的装修帐户。 (虽然 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 Already Created [ yacitus ]”
我肯定没有正确地执行基本的 HTTP 身份验证(无论哪种尝试)。你能发现我的问题吗?也许我应该看看电报里都传了些什么?我以前从没这么做过。有没有我可以使用的 Python API (可能在 pdb 中) ?或者我可以使用其他工具(最好是 Mac OS X) ?