Arovit
Arovit

Reputation: 3709

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.

Upvotes: 0

Views: 337

Answers (2)

falsetru
falsetru

Reputation: 369134

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)

Upvotes: 2

Ayush
Ayush

Reputation: 42450

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.

Upvotes: 1

Related Questions