使用标准库在Python中进行带认证的Curl操作
我想用Python实现下面这个命令:
curl -u username:password http://policeapi2.rkh.co.uk/api/forces
这个命令的详细信息可以在这里找到 http://www.police.uk/api/docs/authentication/
我已经通过浏览器手动登录,并成功进行了身份验证。
我首先尝试了这里的基本身份验证:
voidspace.org.uk/python/articles/authentication.shtml
但是失败了,出现了:
This page isn't protected by authentication.
But we failed for another reason.
然后我尝试根据这个链接进行修改:stackoverflow.com/questions/1990976/convert-a-curl-post-request-to-python-only-using-standard-libary
import urllib2
def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()
req = urllib2.Request("http://policeapi2.rkh.co.uk/api/forces",
headers = {
"Authorization": basic_authorization("username", "password"),
})
f = urllib2.urlopen(req)
print f.read()
结果是:
URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>
我在这个链接上看到:stackoverflow.com/questions/2407126/python-urllib2-basic-auth-problem:
‘问题可能是Python库根据HTTP标准,首先发送一个未认证的请求,只有在收到401的回复后,才会发送正确的凭证。如果Foursquare的服务器没有进行“完全标准的认证”,那么这些库就无法正常工作。’
这和基本身份验证的“此页面未受身份验证保护。”错误有关。
我使用了他们的代码:
import urllib2, base64
request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)'
但仍然出现错误:
URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>
我不知道接下来该尝试什么。我是Python编程的新手,也在学习Curl,现在不知道是我基础掌握得不对,还是出现了更复杂的问题。
感谢任何提供的帮助。
1 个回答
我通过浏览器手动登录,成功进行了身份验证。
你是怎么做到的?
你有没有用FireBug或者其他工具来观察实际发生了什么?
在阅读太多StackOverflow的回答之前,最好先研究一下你之前成功的做法。