简体   繁体   中英

urlencode gives HTTP Error 403: FORBIDDEN

callurl = "http://vgintnh116:8001/master_data/"
params = urllib.urlencode({'res': 'arovit', 'qfields': 'prod' })
f = urllib2.urlopen(callurl, params)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 397, in open
    response = meth(req, response)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 510, in http_response
    'http', request, response, code, msg, hdrs)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 435, in error
    return self._call_chain(*args)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 518, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: FORBIDDEN


But it works with - 
callurl = "http://vgintnh116:8001/master_data/res=arovit&qfields=prod"
f = urllib2.urlopen(callurl)

Please help. I want to use urlencode to avoid handling spaces and extra characters.

If you pass the second argument ( data ), request will be POST instead of GET.

Also, dictionaries in Python does not have order. To guarantee the order, you should use sequence.

callurl = "http://vgintnh116:8001/master_data/"
params = urllib.urlencode([('res', 'arovit'), ('qfields', 'prod')])
f = urllib2.urlopen(callurl + params)

From urllib2 documentation :

the HTTP request will be a POST instead of a GET when the data parameter is provided

In your working example, you are making a GET request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM