更新:基于Lee的评论,我决定将我的代码压缩为一个非常简单的脚本,然后从命令行运行它:
import urllib2
import sys
username = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
print("calling %s with %s:%s\n" % (url, username, password))
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(passman)))
req = urllib2.Request(url)
f = urllib2.urlopen(req)
data = f.read()
print(data)
不幸的是,它仍然不会生成Authorization
标题(每个Wireshark):(
我在通过urllib2发送基本AUTH时遇到问题。我看了这篇文章,并跟随了这个例子。我的代码:
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, "api.foursquare.com", username, password)
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(passman)))
req = urllib2.Request("http://api.foursquare.com/v1/user")
f = urllib2.urlopen(req)
data = f.read()
我通过Wireshark在Wire上看到以下内容:
GET /v1/user HTTP/1.1
Host: api.foursquare.com
Connection: close
Accept-Encoding: gzip
User-Agent: Python-urllib/2.5
与通过curl发送请求相比,您可以看到未发送授权: curl -u user:password http://api.foursquare.com/v1/user
GET /v1/user HTTP/1.1
Authorization: Basic =SNIP=
User-Agent: curl/7.19.4 (universal-apple-darwin10.0) libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3
Host: api.foursquare.com
Accept: */*
由于某种原因,我的代码似乎未发送身份验证-有人看到我丢失了什么吗?
谢谢
-西蒙
'WWW-Authenticate'
标题。您可以使用“try: urllib2.urlopen(req) except urllib2.HTTPError, e: print e.headers
查看此帖子”答案对此进行检查。