The following python curl call has the following successful results:

>>> 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>'

Unfortunately, this call does not successfully translate to urllib2. I receive a different XML response stating that the user did not supply authorization credentials:

>>> import urllib2
>>> # Create a password manager.
... password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
>>> # Add the username and password.
... top_level_url = 'https://qualysapi.qualys.com'
>>> password_mgr.add_password(None, top_level_url, username, password)
>>> handler = urllib2.HTTPBasicAuthHandler(password_mgr)
>>> opener = urllib2.build_opener(handler)
>>> urllib2.install_opener(opener)
>>> headers = {'X-Requested-With':'Demo'}
>>> uri = 'https://qualysapi.qualys.com/qps/rest/3.0/count/was/webapp'
>>> req = urllib2.Request(uri,None,headers)
>>> result = urllib2.urlopen(req)
>>> result
'<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>'

By the way, I receive the same error message with 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>'

I understand that httplib & urllib2 may only work if SSL is compiled into socket, which SSL is compiled into socket's module. In fact, I have used urllib2 successfully for other calls on a different API. The problem is isolated to this one specific API.

What is urllib2 (and httplib) doing differently from curl?

Note: The username and password used are the same in all examples.

Update:

The problem is with the basic auth password manager. When I manually add the basic authorization header, the urllib2 cal works:

>>> 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>'
有帮助吗?

解决方案

From Python urllib2 Basic Auth Problem

The problem [is] that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the ... servers don't do "totally standard authentication" then the libraries won't work.

This particular API does not respond with a 401 Unauthorized on the first attempt, it responds with an XML response containing the message that credentials were not sent with a 200 OK response code.

其他提示

Try setting the user agent, maybe thats whats interfering. urllib2 identifies itself as Python-urllib/x.y (where x and y are the major and minor version numbers of the Python release, e.g. Python-urllib/2.5) this might be whats causing the site to block your request. Take a look at their robots.txt.. here is an example on setting the user agent so as you're script is identified as a browser:

import urllib
import urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top