2016-12-07 54 views
-1

我想写一个python脚本来发送一个HTTP请求,所以我从urllib2库(https://docs.python.org/2/howto/urllib2.html#id6)上的Python文档读取,并拿着身份验证示例代码,但我仍然得到错误...使用python发送一个HTTP请求 - 错误

这里是我的代码(* top_level_url =登录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 

我已经尝试了多种解决方案来解决这个错误,但我一直在获得相同的... 没有人知道我的代码中有什么问题吗? 还是你有另一个代码示例可以工作? (正如我所说的,我试过谷歌前10名的结果...)

感谢先进!

+0

401错误说你是'未经授权的'这意味着(一般来说)你的验证不起作用。检查您的凭证,特别是检查您的https://api.adjust.com/使用的身份验证方法,这与Internet上的所有API都不相同。 – Saksow

+0

您在urllib2中使用的HTTP基本身份验证不适用于跨域,并且您已将top_level_url设置为https://next.adjust.com/#/login,然后您在另一个域上调用url。请参阅:http://stackoverflow.com/q/339244/121199 – filippo

+0

@Saksow 我在脚本中写的用户名和密码 - 是我用来连接网站的确切细节... – Bramat

回答

1

它看起来像你adjust.com使用另一种他们的api认证比你正在使用。

ü应该阅读本文档: https://docs.adjust.com/en/kpi-service/#authentication

而不是使用一个用户名和密码,你应该增加这个HTTP头到您请求:

Authorization: Token token=your_user_token

也可以添加&user_token=your_user_token到您的API调用。

+0

非常感谢 - 这是我第一次使用HTTP请求,你一直很有帮助:) – Bramat