1

我有这样的卷曲呼叫完美的作品:基本认证的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以'/'结尾时不工作

回答

1

在第一次请求您设置:

uri = 'https://api.domain.com/api/work/' 

但是,如果你是做一样的第二轮,你大概意思写为:

uri = 'https://api.server.com/api/work/' 
+0

第二次Python运行是针对同一个uri进行的第二次curl运行的比较。 – paragbaxi 2012-01-30 17:55:31

+0

我想我很困惑,为什么有时你有时会打电话给api.domain.com,有时会打电话给api.server.com。 – Spike 2012-01-30 21:31:41

+0

服务器有两个API版本,每个版本都有不同的内容。 – paragbaxi 2012-01-31 23:10:44

1

Python urllib2 Basic Auth Problem

问题是,根据HTTP标准,Python库首先发送未经身份验证的请求,并且那么只有当它的401重试回答时,才会发送正确的凭证。如果...服务器不执行“完全标准认证”,那么这些库将不起作用。

这个特定的API在第一次尝试时没有响应401重试,它响应一个XML响应,其中包含没有发送凭证的消息。

+0

在发布复制和粘贴样板/逐字回答多个问题时要小心,这些往往会被社区标记为“垃圾”。如果你这样做,那么它通常意味着问题是重复的,所以将它们标记为:http://stackoverflow.com/questions/9495279 – Kev 2012-03-03 00:01:05

+0

谢谢Kev。事实证明,解决方案是一样的,但我只看到了问题的不同症状。它应该仍然是一个复制? – paragbaxi 2012-03-04 22:08:08