我有这样的卷曲呼叫完美的作品:基本认证的urllib2与HTTPPasswordMgrWithDefaultRealm和POST数据
curl -H 'X-Requested-With: SO demo' -d 'parameter=value' https://username:[email protected]/api/work/
我的转换不起作用。
import urllib2
# Create a password manager.
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
top_level_url = 'https://api.server.com'
password_mgr.add_password(None, top_level_url, 'username', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
# Create "opener" (OpenerDirector instance).
opener = urllib2.build_opener(handler)
# Install the opener so all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)
# Create request.
headers = {'X-Requested-With':'SO demo.'}
uri = 'https://api.domain.com/api/work/'
data='parameter=value'
req = urllib2.Request(uri,data,headers)
# Make request to fetch url.
result = urllib2.urlopen(req)
urllib2.HTTPError: HTTP Error 401: Unauthorized
这是我没有得到的。同一个服务器有一个独立的API,类似的代码可以工作,唯一改变的是参数和uri。请注意,cURL调用对两个API调用都起作用。
第二API调用卷曲(的作品):
curl -H 'X-Requested-With: SO demo' -d 'parameter=value' https://username:[email protected]/api2/call.php
等效代码工作如下:
import urllib2
# Create a password manager.
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
top_level_url = 'https://api.server.com'
password_mgr.add_password(None, top_level_url, 'username', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
# Create "opener" (OpenerDirector instance).
opener = urllib2.build_opener(handler)
# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)
# Create request.
headers = {'X-Requested-With':'SO demo.'}
uri = 'https://api.server.com/api2/call.php'
data='parameter=value'
req = urllib2.Request(uri,data,headers)
# Make request to fetch url.
result = urllib2.urlopen(req)
# Read results.
result.read()
为什么urllib2的工作时,URI用 '.PHP' 结束,但当uri以'/'结尾时不工作?
第二次Python运行是针对同一个uri进行的第二次curl运行的比较。 – paragbaxi 2012-01-30 17:55:31
我想我很困惑,为什么有时你有时会打电话给api.domain.com,有时会打电话给api.server.com。 – Spike 2012-01-30 21:31:41
服务器有两个API版本,每个版本都有不同的内容。 – paragbaxi 2012-01-31 23:10:44