Urllib2 raises 403 error while the same request in curl works fine

China☆狼群 提交于 2020-01-06 05:40:28

问题


how would i tranfoms this curl command:

curl -v -d email=onlinecrapbox@gmail.com -d password=mypassword -X POST https://www.toggl.com/api/v6/sessions.json

into urlib2?

Why is this not working:

url=       'https://www.toggl.com/api/v6/sessions.json'
username = 'onlinecrapbox@gmail.com'
password = 'mypassword'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)

authhandler = urllib2.HTTPBasicAuthHandler(passman)

opener = urllib2.build_opener(authhandler)

urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(url)

it gives me this error:

Traceback (most recent call last):
  File "/Users/jorrit/virtualenvs/tiddle/tiddle/troggle/tests.py", line 16, in test_get_troggle_connection
    get_projects()
  File "/Users/jorrit/virtualenvs/tiddle/tiddle/troggle/views.py", line 29, in get_projects
    pagehandle = urllib2.urlopen(url)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open
    response = meth(req, response)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden

回答1:


with requests package, the code would be:

import requests

url = 'https://www.toggl.com/api/v6/sessions.json'
payload = {'email': 'onlinecrapbox@gmail.com',
           'password': 'mypassword'}

r = requests.post(url, data=payload)



回答2:


because your urllib code does something else than what your curl command. Try this instead:

import urllib
import urllib2

url = 'https://www.toggl.com/api/v6/sessions.json'
values = {'email': 'onlinecrapbox@gmail.com',
          'password': 'mypassword'}

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()


来源:https://stackoverflow.com/questions/10062433/urllib2-raises-403-error-while-the-same-request-in-curl-works-fine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!