下面的python curl调用有以下成功结果:
>>> import subprocess
>>> args = [
'curl',
'-H', 'X-Requested-With: Demo',
'https://username:password@qualysapi.qualys.com/qps/rest/3.0/count/was/webapp' ]
>>> xml_output = subprocess.check_output(args).decode('utf-8')
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
138 276 0 276 0 0 190 0 --:--:-- 0:00:01 --:--:-- 315
>>> xml_output
u'<?xml version="1.0" encoding="UTF-8"?>\n<ServiceResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://qualysapi.qualys.com/qps/xsd/3.0/was/webapp.xsd">\n<responseCode>SUCCESS</responseCode>\n <count>33</count>\n</ServiceResponse>'
不幸的是,此调用未成功转换为urllib2。我收到另一个XML响应,声明用户未提供授权凭据:
^{pr2}$顺便说一下,我在httplib中收到了相同的错误消息:
>>> import httplib, base64
>>> auth = 'Basic ' + string.strip(base64.encodestring(username + ':' + password))
>>> h = httplib.HTTPSConnection('qualysapi.qualys.com')
>>> h.request("GET", "/qps/rest/3.0/count/was/webapp/")
>>> r1 = h.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> data1
'<ServiceResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://qualysapi.qualys.com/qps/xsd/3.0/was/webapp.xsd">\n <responseCode>INVALID_CREDENTIALS</responseCode>\n <responseErrorDetails>\n <errorMessage>User did not supply any authentication headers</errorMessage>\n </responseErrorDetails>\n</ServiceResponse>'
我知道httplib和urllib2只有在SSL被编译成socket(SSL被编译到socket的模块中)的情况下才能工作。事实上,我已经成功地将urllib2用于另一个API上的其他调用。这个问题与这个特定的API无关。在
urllib2(和httplib)与curl有什么不同?在
注意:在所有示例中使用的用户名和密码都是相同的。在
更新:
问题出在基本认证密码管理器上。当我手动添加基本授权头时,urllib2 cal起作用:
>>> import base64
>>> base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
>>> req.add_header("Authorization", "Basic %s" % base64string)
>>> # Make request to fetch url.
... result = urllib2.urlopen(req)
>>> # Read xml results.
... xml = result.read()
>>> xml
'<?xml version="1.0" encoding="UTF-8"?>\n<ServiceResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://qualysapi.qualys.com/qps/xsd/3.0/was/webapp.xsd">\n <responseCode>SUCCESS</responseCode>\n <count>33</count>\n</ServiceResponse>'
来自Python urllib2 Basic Auth Problem
这个特定的API在第一次尝试时不会用401未经授权进行响应,而是用一个XML响应响应来响应,其中包含一个消息,即凭证没有用200ok响应代码发送。在
可能是用户设置的干扰。urllib2将自己标识为
Python-urllib/x.y
(其中x和y是Python版本的主要和次要版本号,例如Python-urllib/2.5
),这可能是导致站点阻止您的请求的原因。看看他们的机器人.txt.. 下面是一个关于设置用户代理以便将脚本标识为浏览器的示例:相关问题 更多 >
编程相关推荐