更新: 基于 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 在《火线》上看到了以下内容:
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: */*
出于某种原因,我的代码似乎没有发送身份验证-有人看到我错过了什么吗?
谢谢
Simon