【发布时间】:2017-04-22 04:50:03
【问题描述】:
我正在尝试编写一个 python 脚本来发送一个 HTTP 请求。我从 urllib2 库 (https://docs.python.org/2/howto/urllib2.html#id6) 上的 Python 文档中阅读并获取了带有身份验证的示例代码,但仍然出现错误。
这是我的代码(* top_level_url = 登录网址,a_url = api 请求,可在网络上运行,并显示响应):
import urllib2
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of None.
user='MY_USER_NAME'
passwd='MY_PASSWORD'
top_level_url = "https://next.adjust.com/#/login"
password_mgr.add_password(None, top_level_url, user, passwd)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)
# use the opener to fetch a URL
a_url = 'https://api.adjust.com/kpis/v1/vzpmna78ud8m/cohorts?start_date=2016-12-05&end_date=2016-12-06&kpis=sessions&grouping=os_names,countries'
opener.open(a_url)
# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)
但是当我运行代码时,我得到一个错误:
Traceback (most recent call last):
File "httptest3.py", line 19, in <module>
opener.open(a_url)
File "/usr/lib64/python2.7/urllib2.py", line 437, in open
response = meth(req, response)
File "/usr/lib64/python2.7/urllib2.py", line 550, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib64/python2.7/urllib2.py", line 475, in error
return self._call_chain(*args)
File "/usr/lib64/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/usr/lib64/python2.7/urllib2.py", line 558, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized
我已经尝试了多种解决方案来解决这个错误,但我一直得到相同的解决方案。
有人知道我的代码有什么问题吗? 或者您有其他有效的代码示例吗?
【问题讨论】:
-
401 错误表明您是
Unauthorized,这意味着(通常)您的身份验证不起作用。检查您的凭据,特别是检查您的api.adjust.com 使用的身份验证方法,它在 Internet 的所有 API 上都不相同。 -
您在 urllib2 中使用的 HTTP 基本身份验证不能跨域工作,在这里您将 top_level_url 设置为 next.adjust.com/#/login 然后您调用不同域上的 url。见:stackoverflow.com/q/339244/121199
-
@Saksow 我在脚本中写的用户名和密码 - 是我用来连接到站点的确切详细信息...
标签: python https get-request